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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 13:46:10  来源:igfitidea点击:

Checkbox checked if boolean is true with Angular2

htmlcheckboxangularboolean

提问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 trueand falseand Angular by default uses property binding and I assume the property expects boolean values not strings:

{{}}做字符串插值和字符串化truefalse而 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 checkedinstead 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 FormsModuleimported 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!!

希望这可以帮助!!