如何有条件地添加元素属性,例如复选框的checked

Angular以前的版本有NgAttr个,我想是NgChecked个,它们似乎都提供了我想要的功能.然而,这些属性在Angular 2中似乎不存在,我看不到提供此功能的其他方式.

推荐答案

null删除它:

[attr.checked]="value ? '' : null"

[attr.checked]="value ? 'checked' : null"

提示:

属性vs属性

When the HTML element where you add this binding does not have a property with the name used in the binding (checked in this case) and also no Angular component 或 directive is applied to the same element that has an @Input() checked;, then [xxx]="..." can not be used.

另见What is the difference between properties and attributes in HTML?

当没有这样的属性时,绑定到什么

备选方案是[style.xxx]="..."[attr.xxx]="..."[class.xxx]="...",这取决于你试图完成的目标.

Because <input> only has a checked attribute, but no checked property [attr.checked]="..." is the right way f或 this specific case.

属性只能处理字符串值

A common pitfall is also that f或 [attr.xxx]="..." bindings the value (...) is always stringified. Only properties and @Input()s can receive other value types like boolean, number, object, ...

元素的Most个属性和属性连接在一起并具有相同的名称.

属性属性连接

当绑定到属性时,属性也只从属性接收字符串化的值

属性和属性名称不匹配的两种情况.

Angular was changed since then and knows about these special cases and handles them so that you can bind to <label [f或]=" even though no such property exists (same f或 colspan)

Javascript相关问答推荐

React native在不首次加载时渲染的挂钩比上一次渲染期间渲染的挂钩更多

详细更改参考价值:"

二维数组,过滤并返回带有索引而不是值的新数组

如何使用JavaScript向html元素添加样式

如何通过onClick为一组按钮分配功能;

在贝塞尔曲线的直线上找不到交叉点:(使用@Pomax的bezier.js)

如何解决chrome—extension代码中的错误,它会实时覆盖google—meet的面部图像?'

未捕获错误:在注销后重定向到/login页面时找不到匹配的路由

使用JavaScript重新排序行

如何调用名称在字符串中的实例方法?

为什么useState触发具有相同值的呈现

如何控制Reaction路由加载器中的错误状态?

我正在建立一个基于文本的游戏在react ,我是从JS转换.我怎样才能使变量变呢?

如何在文本字段中输入变量?

连接到游戏的玩家不会在浏览器在线游戏中呈现

使用js构造一个html<;ath&>元素并不能使其正确呈现

如何将数组用作复合函数参数?

为什么客户端没有收到来自服务器的响应消息?

TinyMCE 6导致Data:Image对象通过提供的脚本过度上载

Node.js API-queryAll()中的MarkLogic数据移动