How to use Angular’s NgClass Directive

In previous posts I wrote about property binding with “className” and property binding with “class”. My preferred way of adding conditional or multiple classes is using NgClass.

The syntax for NgClass looks like this:

  
  
string | string[] | Set<string> | { [klass: string]: any }
  

As you can see we can supply single strings, arrays of strings, Sets, and object literals which is great. Here is an example of a NgClass taking a class as a string and array of strings.

  
  
<div [ngClass]="headingStyle"></div>
<div [ngClass]="['headingStyle', 'h1']"></div>
  

Unfortunately we cannot add conditional classes by supplying a string or an array of strings. For that we need to use object literals.

  
  
<div [ngClass]="{headingStyle: condition}">Hello</div>
  

If you want to set keys that contain dashes, you will have to use the string syntax:

  
  
<div [ngClass]="{'heading-style': condition}">Hello</div>
  

Adding multiple classes is easy:

  
  
<div [ngClass]="{
  'header-style': firstCondition,
  'header-color': !secondCondition,
  'header-size': firstCondition && thirdCondition,
}">
Hello
</div>
  

Andy

Front-end Engineer & Designer based in Dublin currently working @IBM.
I write about: Javascript, HTML, CSS, React JS, React Native and UI/UX Design.

Add comment