3

I am new to Angular2. When iam binding attributes i used to do it in following way.

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>

Some times these bindings used to fail .

Then i used the following syntax to bind attribute by suffixing attr. for it.

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>

These syntax used to work like charm some times.

Please help me in learning the difference between these two bindings [attributename] and [attr.attributeName] with there importance in using those particular syntax.

Ravi Teja Kumar Isetty
  • 1,529
  • 3
  • 19
  • 37

1 Answers1

7

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.

Community
  • 1
  • 1
Günter Zöchbauer
  • 558,509
  • 191
  • 1,911
  • 1,506