如何有条件地添加元素属性,例如复选框的checked
?
Angular以前的版本有NgAttr
个,我想是NgChecked
个,它们似乎都提供了我想要的功能.然而,这些属性在Angular 2中似乎不存在,我看不到提供此功能的其他方式.
如何有条件地添加元素属性,例如复选框的checked
?
Angular以前的版本有NgAttr
个,我想是NgChecked
个,它们似乎都提供了我想要的功能.然而,这些属性在Angular 2中似乎不存在,我看不到提供此功能的其他方式.
null
删除它:
[attr.checked]="value ? '' : null"
或
[attr.checked]="value ? 'checked' : null"
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个属性和属性连接在一起并具有相同的名称.
当绑定到属性时,属性也只从属性接收字符串化的值
属性和属性名称不匹配的两种情况.
https://developer.mozilla.或g/en-US/docs/Web/API/HTMLLabelElement/htmlF或 (see the first sentence of the description htmlF或 property reflects the value of the f或
- f或
probably didn't w或k because it's a keyw或d in C 或 JavaScript)
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
)