如何在单击“全部”复选框时选中所有复选框?

时间:2017-08-17 10:18:28

标签: angular angular4-forms

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

component.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;
  }
}

component.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>

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

1 个答案:

答案 0 :(得分:1)

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

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

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