Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 966
Jon Miles Avatar asked Apr 20 '16 13:04

Jon Miles


2 Answers

null removes it:

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

or

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

Hint:

Attribute vs property

When the HTML element where you add this binding does not have a property with the name used in the binding (checked in this case) and also no Angular component or directive is applied to the same element that has an @Input() checked;, then [xxx]="..." can not be used.

See also What is the difference between properties and attributes in HTML?

What to bind to when there is no such property

Alternatives are [style.xxx]="...", [attr.xxx]="...", [class.xxx]="..." depending on what you try to accomplish.

Because <input> only has a checked attribute, but no checked property [attr.checked]="..." is the right way for this specific case.

Attributes can only handle string values

A common pitfall is also that for [attr.xxx]="..." bindings the value (...) is always stringified. Only properties and @Input()s can receive other value types like boolean, number, object, ...

Most properties and attributes of elements are connected and have the same name.

Property-attribute connection

When bound to the attribute the property also only receives the stringified value from the attribute.
When bound to the property the property receives the value bound to it (boolean, number, object, ...) and the attribute again the stringified value.

Two cases where attribute and property names do not match.

  • Error while adding "for" attribute to label in angular 2.0 template
  • https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/htmlFor (see the first sentence of the description htmlFor property reflects the value of the for - for probably didn't work because it's a keyword in C or JavaScript)

  • Why is colspan not a known native attribute in Angular 2?

Angular was changed since then and knows about these special cases and handles them so that you can bind to <label [for]=" even though no such property exists (same for colspan)

like image 125
Günter Zöchbauer Avatar answered Oct 08 '22 05:10

Günter Zöchbauer


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" 
like image 32
Shaishab Roy Avatar answered Oct 08 '22 04:10

Shaishab Roy