Learnitweb

Binding to the style attribute in Angular

In this article we’ll discuss binding to the style attribute in Angular. We use style attribute to define inline styles to elements in HTML. Using style binding we can set styles dynamically.

Binding to the single style

The syntax for binding to single style is:

[style.style-property]="expression"

Example

For example, we can bind the width of a button like the following:

<button type="button" [style.width]="widthOfButton">Save</button>

Here, widthOfButton is a property.

widthOfButton: string = '60px';

Binding to multiple styles

The syntax for binding to multiple styles is:

[style]="expression"

expression can be one of the following:

  1. A list of string where each string represent a style. For example, "width: 100px; background-color: red;".
  2. An object with style names as the keys and style values as the values. For example, {width: '100px', backgroundColor: 'red'}.

Example

For example, in template we can define two buttons.

<button type="button" [style]="buttonStyleList">First button</button>
<button type="button" [style]="buttonStyleObject">Second button</button>

In the component file, declare buttonStyleList and buttonStyleObject.

buttonStyleList = 'width: 60px; background-color: red';
buttonStyleObject = { width: '60px', 'background-color': 'red' };

Note

  • The expression is usually a string. However, unit like em or % can be added.
  • The style property can be written in dash-case or camel case.
<nav [style.background-color]="expression"></nav>
<nav [style.backgroundColor]="expression"></nav>
  • We can not bind an array to [style].
  • [style] binding is preferred over NgStyle directive.

Conclusion

In this article, we discussed binding to the style attribute in Angular. This is very important to know style binding as it is very useful in writing Angular components. We hope this article was informative for you. Happy learning!