Attribute binding in Angular helps you set values for attributes directly. With attribute binding, you can improve accessibility, style your application dynamically, and manage multiple CSS classes or styles simultaneously.
See the live example for a working example containing the code snippets in this guide.
Attribute binding syntax resembles property binding, but instead of an element property between brackets, you precede the name of the attribute with the prefix attr
, followed by a dot. Then, you set the attribute value with an expression that resolves to a string.
<p [attr.attribute-you-are-targeting]="expression"></p>
When the expression resolves to
null
orundefined
, Angular removes the attribute altogether.
One of the primary use cases for attribute binding is to set ARIA attributes.
To bind to an ARIA attribute, type the following:
<!-- create and set an aria attribute for assistive technology --> <button type="button" [attr.aria-label]="actionName">{{actionName}} with Aria</button>
colspan
Another common use case for attribute binding is with the colspan
attribute in tables. Binding to the colspan
attribute helps you to keep your tables programmatically dynamic. Depending on the amount of data that your application populates a table with, the number of columns that a row spans could change.
To use attribute binding with the <td>
attribute colspan
colspan
attribute by using the following syntax: [attr.colspan]
.[attr.colspan]
equal to an expression.In the following example, you bind the colspan
attribute to the expression 1 + 1
.
<!-- expression calculates colspan=2 --> <tr><td [attr.colspan]="1 + 1">One-Two</td></tr>
This binding causes the <tr>
to span two columns.
Sometimes there are differences between the name of property and an attribute.
colspan
is an attribute of<td>
, whilecolSpan
with a capital "S" is a property. When using attribute binding, usecolspan
with a lowercase "s".For more information on how to bind to the
colSpan
property, see thecolspan
andcolSpan
section of Property Binding.
© 2010–2023 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://angular.io/guide/attribute-binding