Attribute and style bindings use similar syntax to property binding. Both use square brackets [].

With attribute binding, instead of placing the name of the element between the brackets, you use the keyword attr, add a dot ., then the name of the attribute followed by an equal sign and an expression. Attribute binding helps you to deal with several styles and CSS classes at the same time by giving you the capability of dynamically style the application that you are developing.

Attribute form

<h3 [attr.name-of-attribute]="expression"</h3>

Bind to a single CSS class

In order to bind to a single CSS class, the keyword class must be used followed by a dot ., and then followed by the name of the CSS class. An equal sign and then an expression is evaluated by Angular. The class is added when the value of the expression is evaluated to true and it is removed when evaluated to false, except if it is evaluated to be undefined.

<p [class.active-user]="activeUser">

Bind to several CSS classes

Binding to several classes can be done in the following format:

[class]=nameOfClassExpression

Example:

[class]='user-class'

You can also use objects, arrays, and maps with key/value pairs:

[class]={first-class: false, second-class: true} //Object

[class]=['first-class', 'second-class'] //Array

Bind to a single style

In order to bind a single style to an element, the keyword style must be used followed by a dot ., then name of the CSS style, and followed by an equal sign with an expression after. The CSS styles can be either written using either snake case or camel case.

Example

<p [style.outline-style]=expression></p>

<p [style.outlineStyle]=expression></p>

Bind to multiple styles

When dealing with multiple styles, the keyword style must be used, followed by an equal sign and then the expression. The expression can be a list of strings or an object. There are no support for arrays.

<img src="avatar.jpg" alt="Avatar" [style]="top: 50px; right: 50px; height: 50px; "></img>

<img src="avatar.jpg" alt="Avatar" [style]="{top: '50px', right: '50px', height: '50px'}></img>

Precedence

The more specific you are in terms of classes, the higher the precedence. For example, class.active-user takes a higher precedence over just class.