Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between binding the attributes with [attr.attributeName] and [attributeName] in Angular2

When I bind attributes, I used to do it like this:

Example1:

  <input type="number" [max]="variableName">

Example2:

<select [(ngModel)]="selectedItem">
  <option *ngFor="let item of itemList" [value]="item.value" [selected]="selectedItem==item.value">{{item.name}}</option>
</select>

Sometimes, these bindings would fail.

But, when I use the following syntax to bind attributes (by suffixing attribute name with attr.):

Example1:

<input type="number" [attr.max]="variableName">

Example2:

 <select [(ngModel)]="selectedItem">
      <option *ngFor="let item of itemList" [value]="item.value" [attr.selected]="selectedItem==item.value">{{item.name}}</option>
    </select>

With this syntax, it worked like charm sometimes.

What is the difference between [attributename] and [attr.attributeName]?

like image 739
Ravi Teja Kumar Isetty Avatar asked Oct 23 '25 02:10

Ravi Teja Kumar Isetty


1 Answers

This is property binding

[selected]="selectedItem==item.value"

This is attribute binding

[attr.selected]="selectedItem==item.value"

See also What is the difference between attribute and property? for the difference between property and attribute.

Property binding works only if the element actually has a property with that name. Some property are automatically reflected to attributes.

Attribute just adds an attribute with that name to the DOM element. Known attributes are read by elements (and @Input()s of Angular components). Custom attributes are just added to the DOM and not processed by the element.

like image 90
Günter Zöchbauer Avatar answered Oct 24 '25 17:10

Günter Zöchbauer