I want to set the id attribute of a HTML element conditionally.
Simple way:
<!-- expression = true -->
<div ng-if="expression">
<a href id="this-one">Anchor with id</a>
</div>
<div ng-if="!expression">
<a href>Anchor without id</a>
</div>
output-if-expression-true = <a href id="this-one">Anchor with id</a> output-if-expression-false= <a href>Anchor without id</a>
Can I avoid this with something like a ternary operator ? for example ...
<a href ng-attr-id="{{expresion ? 'this-one': ''}}">Anchor</a>
Approach 2: We can use the id property inside the element to change the ID using JavaScript.
The id global attribute defines an identifier (ID) which must be unique in the whole document. Its purpose is to identify the element when linking (using a fragment identifier), scripting, or styling (with CSS).
Why do you ask if you already know the answer :-)? Try it out, it is indeed
<a href ng-attr-id="{{expresion ? 'this-one': ''}}">Anchor</a>
The above solution didn't work for me. The following did:
id="{{expression ? 'this-one': 'that-one'}}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With