复选框检查Angular2布尔值是否为true [英] Checkbox checked if boolean is true with Angular2

查看:87
本文介绍了复选框检查Angular2布尔值是否为true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何使用Angular2复选框选中值是否为true,而如果复选框为false,则取消选中该复选框.

I would like to know how to make a checkbox checked if the value is true, and unchecked if false with Angular2.

Adult <input type="checkbox" value="{{person.is_adult}}">

{{person.is_adult}}是boolean

{{person.is_adult}} is a boolean

有人可以建议什么吗?谢谢

Can someone please suggest anything? Thanks

推荐答案

{{}}进行字符串插值并对truefalse进行字符串化,默认情况下Angular使用属性绑定,并且我假设该属性期望布尔值而不是字符串:

{{}} does string interpolation and stringifies true and false and Angular by default uses property binding and I assume the property expects boolean values not strings:

<input type="checkbox" [checked]="person.is_adult">

这可能也很好

<input type="checkbox" attr.checked="{{person.is_adult}}">

由于具有属性绑定,当浏览器将其读入其属性时,浏览器可能会将其从属性(只能是字符串)转换为布尔值.

because with attribute binding the browser might translate it from the attribute (which can only be strings) to boolean when reading it into its property.

它也是checked而不是value

您也可以使用ngModel

<input type="checkbox" [ngModel]"person.is_adult" name="isAdult">
<input type="checkbox" [(ngModel)]"person.is_adult" name="isAdult">

用于单向或双向装订.
如果使用ngModel,请确保已导入FormsModule.

for one-way or two-way binding.
Ensure your have the FormsModule imported if you use ngModel.

这篇关于复选框检查Angular2布尔值是否为true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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