Angular - 2.25-Dynamically apply CSS classes with ngClass

We have already played with *ngIf and ngStyle. A close cousin of ngStyle is ngClass. While ngStyle assigns inline style properties dynamically, ngClass adds or removes CSS classes on an element depending on conditions evaluated at runtime. It is the cleanest way to toggle visual states without manipulating the DOM manually.

To prepare the demo we declare a CSS class in the component styles: .online { color: white; }. This will make the text white whenever the server is online - black on green is hard to read. The class itself is a normal CSS rule; ngClass only decides when to attach it.

Bind ngClass to a class object

  • The directive requires the property-binding syntax: [ngClass].
  • The value is a JavaScript object whose keys are CSS class names and whose values are boolean expressions.
  • The class is attached when the expression evaluates to true and removed when it evaluates to false.

For our example we write <p [ngStyle]="{ backgroundColor: getColor() }" [ngClass]="{ online: serverStatus === 'online' }">...</p>. If the class name contained a dash we would quote it: { 'online-server': serverStatus === 'online' }. We can also extract the condition into a method, like isOnline(), to keep the template tidy.

Inspect the DOM in the browser DevTools: when the server is offline, the paragraph has no online class. As soon as the status becomes online, Angular adds the class to the element and removes it again on the next status change. ngClass is therefore a powerful, declarative way to manage CSS state - and another solid example of a built-in attribute directive that you will use in almost every Angular project.