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 的布尔值是否为真
				
        
 
            
        - CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
 - 失败的 Canvas 360 jquery 插件 2022-01-01
 - Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
 - 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
 - 400或500级别的HTTP响应 2022-01-01
 - Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
 - 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
 - Flexslider 箭头未正确显示 2022-01-01
 - Fetch API 如何获取响应体? 2022-01-01
 - addEventListener 在 IE 11 中不起作用 2022-01-01
 
						
						
						
						
						