0

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>
Roy
  • 7,811
  • 4
  • 24
  • 47
rja
  • 169
  • 2
  • 14
  • Please read this: https://angular.io/api/common/NgClass – Giannis Jul 27 '20 at 09:07
  • 2
    Does this answer your question? [Angular: conditional class with \*ngClass](https://stackoverflow.com/questions/35269179/angular-conditional-class-with-ngclass) – Roy Jul 27 '20 at 09:07
  • another one: https://stackoverflow.com/questions/63008176/ngclass-not-working-in-my-angular-project/63008470#63008470 – Eliseo Jul 27 '20 at 09:36

4 Answers4

3

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>
mbojko
  • 13,503
  • 1
  • 16
  • 26
  • I didn't knew you could do this. ths is very nice for error/verification issues. The ngClass way creates some JSONesque Spaghetti code inside the Html. – Luxusproblem Jul 27 '20 at 09:53
0

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.

Ankit Garg
  • 129
  • 7
0

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

Vna
  • 532
  • 6
  • 19
0

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

Jobelle
  • 2,717
  • 1
  • 15
  • 26