Angular 2 ngClass - apply multiple classes, with class variables Angular 2 ngClass - apply multiple classes, with class variables angular angular

Angular 2 ngClass - apply multiple classes, with class variables


Providing a kind of complete answer to your question,

Do: <input class='form-control' [ngClass]="{'inputExtraClass': true}" placeholder="Not working">

and if you want more than one class or switch between classes you can also do something like

<input class='form-control' [ngClass]="{'inputExtraClass': true, 'notInputExtraClass': !true }" placeholder="Not working">

this way above, it will be either one class or the other

You can also aply any other variation you like using this, or make a property in your component like this one:

toggleClass: boolean = true;

and in your html:

<input class='form-control' [ngClass]="{ 'inputExtraClass': toggleClass, 'notInputExtraClass': !toggleClass }" placeholder="Not working">

same idea, and then you could create a method and change the toggleClass property or whatever :) hope it helped


You can use the "array form" (https://angular.io/api/common/NgClass#description) in this way:

cond1 = true;cond2 = false;smClass = 'form-control-sm';xlClass = 'form-control-xl';<input class='form-control' [ngClass]="[ smClass, cond1 ? 'form-control-lg' : '', cond2 ? xlClass : '' ]">

This will be:

<input class="form-control form-control-sm form-control-lg">


You can use expressions inside ngClass:

<input class='form-control' [ngClass]="(addClassIfTrue) ? 'inputExtraClass' : ''" placeholder="Working">