如何在 Angular 4/5 中访问多个复选框值 [英] How to access multiple checkbox values in Angular 4/5

查看:25
本文介绍了如何在 Angular 4/5 中访问多个复选框值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的复选框中获取值,但我只能获取 true 或 false.

这是我的模板:

Categories

<div class="form-check" *ngFor="let cat of category$|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}}

这是我的组件

this.categories$ = this.storeService.getAllCategories().pipe(map(result => (result as any).data),点击(r => 控制台日志(r)))

我的组件基本上从外部 api 获取类别列表

解决方案

您可以使用如下复选框控件的更改事件,

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

来自 component.ts 文件,

 tempArr: any = { "brands": [] };onChangeCategory(event, cat: any){//使用适当的模型类型而不是 anythis.tempArr.brands.push(cat.name);}

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

解决方案

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

    }

这篇关于如何在 Angular 4/5 中访问多个复选框值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆