How to access multiple checkbox values in Angular 4/5

三世轮回 提交于 2019-11-30 19:44:25

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);

    }

Try this

<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);
      }
  }

working example

You want to get values from checkboxes. Checkbox represents a boolean. So getting true and false is what you should get.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!