Checkbox checked if boolean is true with Angular2(复选框检查了 Angular2 的布尔值是否为真)
问题描述
我想知道如何使用 Angular2 使复选框选中值是否为真,如果值为假则取消选中.
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
推荐答案
{{}} 做字符串插值和字符串化true和falseAngular 默认使用属性绑定,我假设属性需要布尔值而不是字符串:
{{}} 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 的布尔值是否为真的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:复选框检查了 Angular2 的布尔值是否为真
基础教程推荐
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
