[英]Dynamically set attribute on component in html template angular 2
I am trying to set an attribute on a component if a certain expression is true. 如果某个表达式为true,我试图在组件上设置属性。 Could someone give me an example?
有人能举个例子吗?
What I have now: 我现在拥有的:
<div [danger]="inArray(choice.likers, user, id)"></div>
but this does not compile. 但这不编译。
inArray is my own method which returns true or false. inArray是我自己的方法,返回true或false。 What I would like to see is, if the expression returns true, the output will be
我想看到的是,如果表达式返回true,则输出将为
<div danger></div>
In angular 1 there was this: ng-attr-... statement that did exactly the above. 在角度1中有这样的:ng-attr -...声明完全如上所述。
To set an attribute use attribute binding : 要设置属性使用属性绑定 :
<div [attr.danger]="inArray(choice.likers, user, id)"></div>
If you want to show a empty attribute conditionally return empty string or null in inArray()
: 如果要显示空属性,请在
inArray()
有条件地返回空字符串或null:
inArray() {
let value;
if (isInArray) {
value = '';
} else {
value = null;
}
return value;
}
so the attribute will empty or the danger attribute dont exist. 所以该属性将为空或危险属性不存在。 The result is:
结果是:
<div danger></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.