Creating dynamic styles in web applications can be a real pain. Luckily with Angular 2 we have multiple ways to handle our dynamic CSS and CSS classes with the new template syntax as well as some built in directives.

Angular Template Property Syntax

First lets look at how we would change a <div> color property in pure JavaScript.

let myDiv = document.getElementById('my-div'); = 'orange';   // updating the div via its properties

Now lets look at the primitives the new Angular 2 syntax gives us out of the box. Using the [property] syntax we can easily access any element or component properties.

<div [style.color]="'orange'">style using property syntax, this text is orange</div>

In the example above we can directly access the style property of our div element. This is different than an attribute. Properties are the properties defined on our DOM object just like the one we updated in our first example with just plain JavaScript.

We can also use the Angular 2 property syntax to add CSS classes to elements.

<div [className]="'blue'">CSS class using property syntax, this text is blue</div>

ngStyle and ngClass

Out of the box with the new syntax we don’t need special ng-class or ng-style directives like in Angular 1. But with Angular 2 we still have these built in directives. These directives offer syntactic sugar for more complex ways of altering our element styles. First lets look at ngStyle.

<div [ngStyle]="{'color': 'blue', 'font-size': '24px', 'font-weight': 'bold'}">
  style using ngStyle

In this example using ngStyle we can easily style multiple properties of our element. We also can bind these properties to values that can be updated by the user or our components.

<div [ngStyle]="{'color': color, 'font-size': size, 'font-weight': 'bold'}">
  style using ngStyle

<input [(ngModel)]="color" />
<button (click)="size = size + 1">+</button>
<button (click)="size = size - 1">-</button>

Next lets look at the ngClass directive and the options it provides to update classes on our components and HTML elements.

<div [ngClass]="['bold-text', 'green']">array of classes</div>
<div [ngClass]="'italic-text blue'">string of classes</div>
<div [ngClass]="{'small-text': true, 'red': true}">object of classes</div>

Same as ngStyle the ngClass allows multiple ways to add and toggle our CSS. We can bind these classes directly to our component properties to update them dynamically as needed. Between the new template syntax and a few more directives our Angular 2 apps are easier than ever to style. Click the demo button below to see a working plnkr of the code.