Learnitweb

Attribute binding in Angular

In this article we’ll discuss attribute binding in Angular. Angular supports both property binding as well as attribute binding. It is recommended to use property binding, if possible. However, it is not always possible to use property binding in case there is no property to bind. In this case attribute binding can be used. colspan, aria-label and svg are few examples of attributes where attribute binding can be used. Attribute binding can be used to dynamically apply classes and styles in the application.

Attribute binding syntax

Attribute binding syntax is similar to property binding syntax, attribute enclosed in square brackets. The only change is attribute name is prefixed with attr and a dot (.). For example:

<p [attr.target-attribute]="expression"></p>

The condition here for attribute binding is that expression should not resolve to null or undefined. If the expression is resolved to null or undefined then Angular removes the attribute.

Example of attribute binding

Binding colspan attribute

colspan attribute is used to define the number of columns a row could span. colspan = "3" means a row (<tr>) will span to three columns. colspan can make your tables dynamic. We can apply attribute binding to colspan attribute as following:

<tr><td [attr.colspan]="1 + 1">Column Span of two</td></tr>

Binding ARIA attributes

Accessible Rich Internet Applications (ARIA) is a set of attributes that makes web applications more accessible to people with disabilities. Following is an example of setting aria-label attribute.

<button [attr.aria-label]="buttonAction">{{buttonAction}}</button>

Conclusion

There are two other important attribute binding that we should know. Binding to class attribute and binding to style attribute. We’ll discuss these in upcoming articles.

This was a rather short article but very important one. We hope this article was informative for you. Happy learning!