How to access multiple checkbox values in Angular 4/5

不羁的心 提交于 2019-11-30 04:13:51

问题


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


回答1:


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

    }



回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/50173409/how-to-access-multiple-checkbox-values-in-angular-4-5

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