Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why sometimes we need [attr.] prefix for binding

When binding in general we only need to add []

Working example:

<input [type]="myInputType" [(ngModel)]="myValue" />

But sometimes its is mandatory to use [attr.]

Example where [attr.] is mandatory:

<svg>
    <path [attr.fill]="part.color[attr.d]="part.d"
    [attr.transform]="part.transform"></path>
</svg>

I cannot determine if I need or not (only empirically by actually trying it), which is disturbing. What is the rule?

like image 913
David Faure Avatar asked Dec 05 '25 05:12

David Faure


1 Answers

Without attr. Angular will bind to a property. A property isn't available in the DOM for CSS or querySelector.

Some properties are reflected to attributes by the element itself, which again makes it available for CSS or querying (class, disabled, ...).

See also Properties and Attributes in HTML

If there is no property with that name, you can only bind to an attribute. For that Angular requires attr.

like image 161
Günter Zöchbauer Avatar answered Dec 06 '25 17:12

Günter Zöchbauer