How to access multiple checkbox values in Angular 4/5

user5431121 picture user5431121 · May 4, 2018 · Viewed 24.8k times · Source

I want to get the values from my checkboxes but I can only get true or false.

Here is my template:

<h4>Categories</h4>
<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}}">
    <label class="form-check-label" for="{{cat.name}}">
        {{cat.name}}
    </label>
</div>

Here is my component

this.categories$ = this.storeService.getAllCategories().pipe(
    map(result => (result as any).data),
    tap(r => console.log(r))
)

My component basically gets a list of the categories from an external api

enter image description here

Answer

Pardeep Jain picture Pardeep Jain · May 4, 2018

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