31

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.

0

1 Answer 1

66

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>
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you for your comment muetzerich. This code allows me to set the value of the attribute dynamically but what I would like to achieve is to set the attribute itself.
To clarify: the output with your code is: danger="true", but I would like to only set the attribute not give it a value.
try this [attr.danger]="inArray(choice.likers, user, id) ? true : null" -> null remove the danger attribute
I am sorry to say but still the same problem: danger="true". Seems like this is not working for attributes. Although I found an example in the docs that does work [disabled]. I will try to create a plunkr.
an empty string '' instead of true seems to do the trick. Thanks!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.