I am working on angular 4. I have a requirement of selecting all services (checkbox) when I check checkbox named "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>
I have used this code and every thing was working properly except check all functionality.
You could tap into the form value and use that together with [checked]
attribute for your checkboxes. Rather ugly perhaps, but works :)
<input [class]="industry.value"
type="checkbox"
[checked]="form.value[industry.value][i]['status']"
formControlName="status" >