How to access multiple checkbox values in Angular 4/5
You can simply use the change
event to get an event when the checkbox clicked like below -
<div class="form-check" *ngFor="let cat of categories">
<input class="form-check-input" (change)="onChange(cat.name, $event.target.checked)"name="{{ cat.name }}" type="checkbox" id="{{cat.name}}">
<label class="form-check-label" for="{{cat.name}}">
{{cat.name}}
</label>
</div>
onChange(email:string, isChecked: boolean) {
if(isChecked) {
this.emailFormArray.push(email);
} else {
let index = this.emailFormArray.indexOf(email);
this.emailFormArray.splice(index,1);
}
}
Update
In case of check all checkboxes you can loop over them -
et checkBoxes = document.querySelectorAll('.form-check-input');
checkBoxes.forEach(ele => ele.click())
working example
You can use change event with checkbox control like below,
<div class="form-check" *ngFor="let cat of categories$|async">
<input class="form-check-input" [(ngModel)]="cat.id" name="{{ cat.name }}" type="checkbox" id="{{cat.name}}" (change)="onChangeCategory($event, cat)">
<label class="form-check-label" for="{{cat.name}}">
{{cat.name}}
</label>
</div>
From component.ts file,
tempArr: any = { "brands": [] };
onChangeCategory(event, cat: any){ // Use appropriate model type instead of any
this.tempArr.brands.push(cat.name);
}
it's unnecesary use event change and use auxiliar variable to store the array. You can simply use a getter to get the value
If we use as [(ngModel)] 'cat.isChecked'
<div class="form-check" *ngFor="let cat of categories">
<input class="form-check-input" [(ngModel)]="cat.isChecked" name="{{ cat.name }}" type="checkbox" id="{{cat.name}}">
<label class="form-check-label" for="{{cat.name}}">
{{cat.name}}
</label>
</div>
We can has some like:
get values()
{
return this.categories.filter(x=>x.isChecked).map(x=>x.id)
}
If we need a "check all" we can use
<input #checkAll type="checkbox" (change)="selectAll(checkAll.checked)">
selectAll(checked:any)
{
this.categories.forEach(x=>x.isChecked=checked)
}
See the stackblitz