How to access multiple checkbox values in Angular

2020-03-01 20:24发布

问题:

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.