添加带有角度ReactiveForms的多个复选框

时间:2019-01-29 05:39:35

标签: angular typescript modal-dialog

早上好

我一直在管理模式窗口中的复选框表。此模式是子组件。父级将一组数据传递给子级,然后子级以模态形式显示它。

我的问题是角度组件的生命周期,我首先有一个this._prestations未定义,而关联的请求在浏览器中显示200响应。我怀疑angular希望在将数据有效传递到子组件之前从数据中构建子组件。我不知道如何处理,我尝试了ng-ifs多次,并在.ts中添加了条件,例如!this._prestations == undefined,没有机会!

您能指出我的错误(在概念和/或编码方面),以便我可以学习一些东西。或者只是想知道我应该朝哪个方向发展。

父组件

parent.html(已删除的不必要信息):

<app-devis-select-prestation  [prestations]="this.prestations" 
                                (select)="select($event)"
                                *ngIf="selectedPrestation==null">
  </app-devis-select-prestation>

parent.ts

export class DevisComponent implements OnInit {

  clients;
  familles;
  prestations=null;
  msg:String; typeMsg:number;
  _TITLE;
  selectedClient:Object =null;
  selectedPrestation:Array<Object>;
  buttons=[
    {id:1, name:'Modifier'},
    {id:2, name:'Enregistrer'}
  ];
  _keyInfo=['Clients','Prestations','Matériels'];

  constructor(  private cs:ClientService, 
                private ps:PrestationService,
                private ms:MaterielService) { }

  ngOnInit() {
    this._TITLE = "Créer un devis";
    this.cs.getIdentityAndLocation().subscribe(
      data => this.clients = data,
      err => this.msg = err
    )
    this.ps.getPrestations().subscribe(
      data => this.prestations = data,
      err => this.msg = err
    )

  }

  select(event){
    if(event.table==1){
      this.selectedClient = event.selection
    }else if(event.table==2){
      this.selectedPrestation = event.selection
    }
  }

  operate(event){
    console.log(event.id+ " " + event.text)

    if(event.id==1 && event.text == 'Modifier'){
      this.selectedClient=null
    }else if(event.id==2 && event.text =='Enregistrer'){
      console.log("click sur le bouton enregistrer")
    }else{
      console.log("error")
    }
  }


}

子组件

Child.html

<button     type="button" 
            class="btn btn-success btn-sm" 
            data-toggle="modal" 
            data-target="#showPrestations" 
            (click)="onClick($event)" 
            *ngIf="selectedPrestations.length==0">{{buttons}}</button>
<table class="table table-borderless table-hover table-sm" *ngIf="!selectedPrestations.length==0">
    <thead>
        <th>libelle</th>
        <th>Montant</th>
        <th>Quantité</th>
        <th>Total</th>
    </thead>
    <tbody>
        <tr *ngFor="let prestation of selectedPrestations">
            <td>{{prestation.libelle}}</td>
            <td>{{prestation.montant}}</td>
            <td>
                <input type="number" (blur)="setQuantity()"/>
            </td>
            <td>
                <p>{{total}}</p>
            </td>


        </tr>
    </tbody>
</table>


<!--Modale-->
<div    class="modal fade" 
        id="showPrestations" 
        tabindex="-1" 
        role="dialog" 
        aria-labelledby="showPrestationTitle" 
        aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <form [formGroup]="form" (submit)="selectPrestations(this.form.value)">
            <div class="modal-header">
                <h5 class="modal-title" id="showPrestationTitle">Sélection des prestations</h5>
            </div>

            <div class="modal-body">

                <table class="table table-borderless table-hover table-sm">
                    <thead>
                        <th *ngFor="let header of headers">{{header.header}}</th>
                        <th>Sélection</th>
                    </thead>
                    <tbody formArrayName="choix">
                        <tr *ngFor="let prestation of prestations">
                            <td *ngFor="let header of headers">
                                <label [for]=prestation.libelle >{{prestation[header.key]}}</label>

                            </td>
                            <td>
                                <input  [name]="prestation.libelle" 
                                        type="checkbox" 
                                        [value]="prestation.id" 
                                        [formControlName]="prestation.id"
                                        (change)="onCheck($event, prestation.id)"
                                        />
                                {{prestation.id}}
                            </td>
                        </tr>
                    </tbody>
                </table>


            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Fermer</button>
                <button class="btn btn-success btn-sm" type="submit" >Enregistrer</button>
                <app-view-msg [text]="this.msg" [type]="this.type" *ngIf="!this.msg==null"></app-view-msg>
            </div>
        </form>
        </div>
    </div>

</div>

child.ts:

export class DevisSelectPrestationComponent implements OnInit {


 private _prestations:Array<Object>;
 private headers = [
   {header: "Libelle", key:"libelle"},
   {header: "Montant", key:"montant"}
 ]
 private form:FormGroup;
 private buttons = ['Ajouter des prestations'];
 private selectedPrestations:Array<Object> =[];
 private type;
 private qtity;
 private total;
text=null;

 constructor  (private fb:FormBuilder){ }

ngOnInit(){
  console.log(this.selectedPrestations.length)
  this.form = this.fb.group({
   choix :this.fb.array([])
 })
}

ngOnChanges(changes:SimpleChanges){
  const prestationsChange = changes['prestations'];
  console.log(this._prestations)
  this.addChoix()

}


 @Input()
 set prestations(prestations:Array<Object>){
   this._prestations = prestations

 }
 get prestations():Array<Object>{return this._prestations}

 @Output() select = new EventEmitter<Object>();
 button(event){
   this.select.emit(event)
 }

 selectPrestations(formData){
  let choix = formData.choix
  console.log(choix)
  let result = [];
  choix.forEach(element => {
    result = [...result, this._prestations[element-1]]
  });
  this.selectedPrestations = result;
  console.log(this.selectedPrestations)

}

// thought to put this method into the input setter but outputs this_prestations is undefined
addChoix(){
  this._prestations.forEach(element=>{
    this.choix.push(this.fb.control(''))
  })

}

get choix(){return this.form.get('choix') as FormArray}

onClick(event){
  console.log("click")
  this.text = "Enregistrement effectué"
  this.type = 1
}

onCheck(event, id){ //ok
  if(event.target.checked){
    console.log(id)
    this.choix.push(this.fb.control(id))
  }else{
    let i = 0;
    this.choix.controls.forEach(element => {
      if(element.value == event.target.value){
        this.choix.removeAt(i)
        console.log("index" +i+" unchecked")
      }
      i++;
    });
    console.log("unchecked")
  }
}

setQuantity(){

}

calculate (montant, qtity){
  this.total = montant * qtity

}

}

0 个答案:

没有答案