Html 使用Angular2检查布尔值是否为真的复选框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39233130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checkbox checked if boolean is true with Angular2
提问by jiji
I would like to know how to make a checkbox checked if the value is true, and unchecked if false with Angular2
.
我想知道如何检查复选框是否值为真,如果值为假则取消选中Angular2
。
Adult <input type="checkbox" value="{{person.is_adult}}">
{{person.is_adult}} is a boolean
{{person.is_adult}} 是 boolean
Can someone please suggest anything? Thanks
有人可以建议什么吗?谢谢
回答by Günter Z?chbauer
{{}}
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:
{{}}
做字符串插值和字符串化true
,false
而 Angular 默认使用属性绑定,我假设该属性需要布尔值而不是字符串:
<input type="checkbox" [checked]="person.is_adult">
This might work as well
这也可能有效
<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.
因为使用属性绑定,浏览器在将其读入其属性时可能会将其从属性(只能是字符串)转换为布尔值。
It is also checked
instead of value
它也checked
代替value
You can also use ngModel
你也可以使用 ngModel
<input type="checkbox" [ngModel]"person.is_adult" name="isAdult">
<input type="checkbox" [(ngModel)]"person.is_adult" name="isAdult">
for one-way or two-way binding.
Ensure your have the FormsModule
imported if you use ngModel
.
用于单向或双向绑定。
确保您已在FormsModule
如果您使用的进口ngModel
。
回答by Madhu Ranjan
you are missing square bracket around checked
你在检查周围缺少方括号
<input type="checkbox" [checked]="person.is_adult">
Hope this helps!!
希望这可以帮助!!