简体   繁体   中英

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. 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. What I would like to see is, if the expression returns true, the output will be

<div danger></div>

In angular 1 there was this: ng-attr-... statement that did exactly the above.

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() {
    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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM