How to add conditional attribute in Angular 2?

How to add conditional attribute in Angular 2?

How can I conditionally add an element attribute e.g. the checked of a checkbox?
Previous versions of Angular had NgAttr and I think NgChecked which all seem to provide the functionality that I’m after. However, these attributes do not appear to exist in Angular 2 and I see no other way of providing this functionality.


Solution 1:

null removes it:

[attr.checked]="value ? '' : null"


[attr.checked]="value ? 'checked' : null"

Solution 2:

in angular-2 attribute syntax is

<div [attr.role]="myAriaRole">

Binds attribute role to the result of expression myAriaRole.

so can use like

[attr.role]="myAriaRole ? true: null"

Solution 3:

Refining Günter Zöchbauer answer:

This appears to be different now. I was trying to do this to conditionally apply an href attribute to an anchor tag. You must use undefined for the ‘do not apply’ case. As an example, I’ll demonstrate with a link conditionally having an href attribute applied.

An anchor tag without an href attribute becomes plain text, indicating a placeholder for a link, per the hyperlink spec.

Related:  HtmlWebpackPlugin injects relative path files which breaks when loading non-root website paths

For my navigation, I have a list of links, but one of those links represents the current page. I didn’t want the current page link to be a link, but still want it to appear in the list (it has some custom styles, but this example is simplified).

<a [attr.href]="currentUrl !== link.url ? link.url : undefined">

This is cleaner than using two *ngIf’s on a span and anchor tag, I think.

Solution 4:

If it’s an input element you can write something like….
<input type="radio" [checked]="condition"> The value of condition must be true or false.

Also for style attributes…
<h4 [style.color]="'red'">Some text</h4>

Solution 5:

you can use this.

<span [attr.checked]="val? true : false"> </span>

Solution 6:

Inline-Maps are handy, too.

They’re a little more explicit & readable as well.

[class]="{ 'true': 'active', 'false': 'inactive', 'true&false': 'some-other-class' }[ trinaryBoolean ]"

Just another way of accomplishing the same thing, in case you don’t like the ternary syntax or ngIfs (etc).