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]?
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.
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