rja
rja

Reputation: 169

how to implement if-else condition with ng-class?

I am trying to use two different grid columns binding to ng-class with if-else condition. I am unable to do it properly. Can someone guide where I am doing wrong. thanks.

HTML

<div ng-class="{'col-md-11': test1 === null, 'col-md-6' : test1 !== null}" *ngIf="(test !== null)">
<div>
<div ng-class="{'col-md-11': test === null, 'col-md-6' : test !== null}" *ngIf="(test1 !== null)">
<div>

Upvotes: 0

Views: 1020

Answers (4)

Jobelle
Jobelle

Reputation: 2834

You can include the condition like below in ngClass.

<div [ngClass]="{'col-md-11': test1 === null, 'col-md-6' : test1 !== null}">
<div>

Here col-md-11 will ve added only if the test value is null and col-md-6 will be added if test1 is not null

Upvotes: 0

Vna
Vna

Reputation: 542

You can directly use ternary condition for ngClass

<div [ngClass]="test1 ? 'col-md-6' : 'col-md-11'" *ngIf="(test !== null)">
<div>

https://stackblitz.com/edit/angular-ivy-ggcr4l

Upvotes: 0

mbojko
mbojko

Reputation: 14679

You can use [class] instead of ngClass.

<div [class.col-md-11]="test1 === null" [class.col-md-6]="test1 !== null" *ngIf="test !== null"></div>
<div [class.col-md-11]="test === null" [class.col-md-6]="test !== null" *ngIf="test !== null"></div>

Upvotes: 3

Ankit Garg
Ankit Garg

Reputation: 149

You can use something like below code.

[ngClass]="{'highlight': expression}"

highlight is class name which should be applied when expression returns a boolean value. Expression can be a function also. Main point to remember is you should get value in boolean type.

[ngClass]="{'highlight': expression, 'highlight1': expression}"

If you want a else condition you can add one more class and execute the same expression. So whichever is true it will apply that class.

For more details you can always visit ANGULAR IO website. It will provide you all the answers.

Upvotes: 0

Related Questions