1

我正在研究角度 4。当我选中名为“All”的复选框时,我需要选择所有服务(复选框)。

组件.ts

industries : any = [
  {
     "industry_name" : "Lawn Care", 
     "value" : "lawn_care",
     "service_categories" : [
        {"service_name" : "Fixed Rate",  "status" : true },
        {"service_name" : "Hourly",      "status" : true },
        {"service_name" : "Re-Clean",    "status" : true },
        {"service_name" : "Re-Clean 2",  "status" : true }
      ]
   },...
];

form : FormGroup;
constructor( private formBuilder : FormBuilder){
   this.form = this.formBuilder.group({});
}
ngOnInit(){
   for(let industry of this.industries)
   {
      let fieldName = industry.value;
      this.form.addControl(fieldName, new FormArray([]) );

      let serviceArray = <FormArray>this.form.controls[fieldName];
      for(let service of industry.service_categories)
      {
        let control = this.formBuilder.group({
          service_name  : [service.service_name],
          status        : [service.status] 
        });
        serviceArray.push(control);
      }
    }
}
selectAll(event, industry)
{
  let fieldName = industry.value;
  for(let service of this.form.controls[fieldName].value)
  {
     (event.target.checked) ? service.status = true : service.status = false;
  }
}

组件.html

 <div *ngFor="let industry of industries">
       <label>{{industry?.industry_name}}</label>
       <div>
         <div *ngFor="let category of industry?.service_categories; let i=index" [formArrayName]="industry.value" >
            <ng-container [formGroupName]="i">
                <input [class]="industry.value" type="checkbox" formControlName="status" >
                <span>{{category?.service_name}}</span>
            </ng-container>
        </div>
        <div>
           <input type="checkbox" (change)="selectAll($event, industry)">
           <span>All</span>
        </div>
      </div>
    </div>

我已经使用了这段代码,除了检查所有功能外,一切都正常工作。

4

1 回答 1

1

您可以利用表单值并将其与[checked]复选框的属性一起使用。也许相当丑陋,但有效:)

<input [class]="industry.value" 
       type="checkbox" 
       [checked]="form.value[industry.value][i]['status']" 
       formControlName="status" >

演示: http ://plnkr.co/edit/HI3h5nkbRwaQ9fj2jihZ?p=preview

于 2017-08-17T11:37:00.020 回答