Posted by Arjun on Monday 12th June 2017

How to Apply CSS Classes Conditionally in Angular 2

How to ngClass Angular

Angular 2 provide different ways to apply class to the elements based on certain conditions. In this post I would like to show you couple of ways to conditionally applying class to a DOM element in Angular 2 with ngClass.

Methods to Apply CSS Classes Conditionally

#1
<div [ngClass.has-errors]="form.errors.email"></div>

#2
<div [ngClass]="{'has-errors': form.errors.email}"></div>

#3
<div [ngClass]="{1:'class-step-1',2:'class-step-2',3:'class-step-3',5:'class-step-5'}[step]"></div>

#4
<div [ngClass]="form.errors.email ? 'has-errors' : 'has-success'"></div>