W3cubDocs

/Angular

Attribute binding

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.

Prerequisites

Syntax

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 or undefined, Angular removes the attribute altogether.

Binding ARIA attributes

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>

Binding to 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

  1. Specify the colspan attribute by using the following syntax: [attr.colspan].
  2. Set [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>, while colSpan with a capital "S" is a property. When using attribute binding, use colspan with a lowercase "s".

For more information on how to bind to the colSpan property, see the colspan and colSpan section of Property Binding.

What’s next

Last reviewed on Mon May 02 2022

© 2010–2023 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://angular.io/guide/attribute-binding