如何知道是否在角度2中单击了复选框 [英] How to know whether checkbox is clicked or not in angular 2

查看:46
本文介绍了如何知道是否在角度2中单击了复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个复选框,如下所示

I am having multiple checkbox as follows

moduleNameList = ['test1', 'test2', 'test3', 'test4']
<li *ngFor="let module of moduleNameList">
<input [value]="module" type="checkbox"> {{module}}<br>
</li>

用户可以单击任何复选框,最后,一旦单击按钮,我想知道用户检查的值是什么. 谁可以帮我这个事? 点击此处查看带有按钮的复选框

User can click on any check box, finally once he click on a button I want to know what are values user checked. Can any one help me on this? Click here to see the check boxes with button

推荐答案

我认为最简单的方法是使用新属性(例如,将checked作为ngModel来切换布尔值),将项目制作为对象选中true时相反,反之亦然.

I think the easiest way is to make the items to objects, with a new property, for example checked as the ngModel that toggles the boolean value of true when checked and vice versa.

moduleNameList=[{name:'test1', checked: false},{name:'test2', checked: false},
                 {name:'test3',checked:false}]

模板:

<li *ngFor="let module of moduleNameList">
  <input [value]="module" type="checkbox" [(ngModel)]="module.checked"> 
    {{module.name}}
</li>

现在,您可以在单击按钮时迭代该数组,并查看哪些对象的checked属性为true.

Now you can iterate that array on button click and see which objects have the checked property as true.

编辑:由于OP注意到我的错误,因此进行了小幅更改!我们应该使用[value]而不是[ngValue]

small change as OP noticed my error! We should use [value] instead of [ngValue]

这篇关于如何知道是否在角度2中单击了复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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