简体   繁体   English

Angular2,在多个复选框列表中获取选中复选框的值

[英]Angular2 , in multiple checkboxes list get the value of checked checkbox

I'm using multiple checkboxes and on click of any of the checkbox need to push the value in array if it is checked true and remove from the array if checked false.我正在使用多个复选框,单击任何复选框时,如果选中为真,则需要将值推送到数组中,如果选中为假,则从数组中删除。

Is there any way to check that the checkbox is checked or unchecked on a click like jquery?有什么方法可以检查复选框是否选中或取消选中像 jquery 这样的点击?

Further to the comment:进一步的评论:

HTML Element: HTML 元素:

<input type="checkbox" (click)="onClick($event)" />

TypeScript Code:打字稿代码:

onClick(event: any) {
 console.log(event); //you can explore the event object and use the values as per requirement
}

Check this similar post that solves the issue for multiple checkboxes.检查解决多个复选框问题的类似帖子。 angular-2-get-values-of-multiple-checked-checkboxes angular-2-get-values-of-multiple-checked-checkboxes

I have included here a simple implementation for checkbox states in angular2我在这里包含了 angular2 中复选框状态的简单实现

 import {Component, NgModule } from '@angular/core'; @Component({ selector: 'test-app', template: ` <label for="options">Options :</label> <div *ngFor="let cbItem of cbArr"> <label> <input type="checkbox" name="options" value="{{cbItem}}" [checked]="cbChecked.indexOf(cbItem) >= 0" (change)="updateCheckedOptions(cbItem, $event)"/> {{cbItem}} </label> </div> <button (click)="updateOptions()">Post</button> ` }) export class TestComponent{ cbArr: string[]; cbChecked: string[]; constructor() { this.cbArr = ['OptionA', 'OptionB', 'OptionC']; this.cbChecked = ['OptionB']; } updateCheckedOptions(chBox, event) { var cbIdx = this.cbChecked.indexOf(chBox); if(event.target.checked) { if(cbIdx < 0 ) this.cbChecked.push(chBox); } else { if(cbIdx >= 0 ) this.cbChecked.splice(cbIdx,1); } } updateOptions() { console.log(this.cbChecked); } }

Here cbArr stores the values or options needed and cbChecked stores the selected values.此处 cbArr 存储所需的值或选项,而 cbChecked 存储选定的值。 On changing the checkbox value, cbChecked is updated id checkbox item is updated into it and finally on click of "Post" button, you can simply print out the cbChecked values for the list of items under selection.在更改复选框值时,cbChecked 被更新 id 复选框项目被更新到其中,最后单击“发布”按钮,您可以简单地打印出所选项目列表的 cbChecked 值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM