Mohammad Ali
Mohammad Ali

Reputation: 352

Angular 2 ngClass - apply multiple classes, with class variables

I'm trying to add variable-driven class(es) to an element, along with other classes using ngClass.

Example:

// inputExtraClass = 'form-control-sm'

// Working
<input class='form-control' [ngClass]="inputExtraClass" placeholder="Working">

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

Plunker

Upvotes: 9

Views: 14360

Answers (4)

Bluerain
Bluerain

Reputation: 506

If someone wants to directly use the class name with the dynamic variables, without any conditions, then they can use this way.

<div class="card-table second" ngClass="{{source}} {{currentMode}}">

Upvotes: 0

Herbertusz
Herbertusz

Reputation: 1241

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">

Upvotes: 5

Alejandro Camba
Alejandro Camba

Reputation: 988

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

Upvotes: 12

yanbu
yanbu

Reputation: 183

You can use expressions inside ngClass:

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

Upvotes: 0

Related Questions