Managing styles with Angular directives

Managing styles with Angular directives

Angular provides us with various ways to manipulate styles inside an element in a template of our components. I always have problems remembering the correct syntax, hence the idea to write this fiche.

Binding

First of all, for the simplest cases we can use class and style binding

<element [style.max-width.px]="maxWidth"></element>
<element [class.my_class]="condition"></element>

For more complex cases, Angular provides us with built-in ngStyle and ngClass directives. Both are delivered within the CommonModule.

ngStyle

NgStyle directive allows you to dynamically set CSS styles on an element based on a condition or an expression. With ngStyle, you can bind to an object literal containing style definition.

<element [ngStyle]="styleObject"></element>

For example, we can set the maximum width of an element:

<element [ngStyle]="{'max-width.px': widthExpression}"></element>

ngClass

For class manipulation we can use ngClass directive. It works in a similar way to ngStyle, but it can be used in three different ways - using string, Array or Object. The following are examples of usage:

<element [ngClass]="condition ? 'class1 class2' : 'class3'"></element>
<element [ngClass]="['class1', 'class2']"></element>
<element [ngClass]="{'class1': condition1', 'class2': condition2 }"></element>