'Can ngClass use ternary operator in Angular 2?

In Angular 1, the code below works well.

<div ng-class="$varA === $varB ? 'css-class-1' : 'css-class-2'">

But when I try to do similar thing in Angular 2. It does not work.

I already added directives: [NgClass]

<div [ngClass]="varA === varB ? 'css-class-1' : 'css-class-2'">

How should I write in Angular 2, thanks!

EDIT: It was my mistake, I accidentally added { } to the whole varA === varB ? 'css-class-1' : 'css-class-2'. So ngClass still can use ternary operator in Angular 2.



Solution 1:[1]

Yes. What you wrote works:

<div [ngClass]="varA === varB ? 'css-class-1' : 'css-class-2'">

Plunker

The result of the expression on the the right-hand side has to evaluate to one of the following:

  • a string of space-delimited CSS class names (this is what your expression returns)
  • an Array of CSS class names
  • an Object, with CSS class names as keys, and booleans as values

Maybe you had some other error in your code?

Solution 2:[2]

<div [ngClass]="{'css-class-1':varA === varB, 'css-class-2': varA !== varB}">

See also https://angular.io/api/common/NgClass

Solution 3:[3]

You can try the followings.....

For ternary operator use:

[ngClass]="condition1==condition2?'class-1':'class-2'"

For multiple condition use:

[ngClass]="{'class-1':condition1==condition2, 'class-2': condition3==condition4}"

thnks...

Solution 4:[4]

you can try this:

maybe this example, will make it clearer:

<div [ngClass]="salesVolume <= 55_000 ? 'bg_green' : 'bg_red' " >

bg_green and bg_red are 2 class styles defined in your style.css file

Solution 5:[5]

you can try this:

<div class="css-class-3 css-class-4" [ngClass]="{'css-class-1': varA === varB, 'css-class-2': !(varA === varB)}">

this worked for me

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 aloisdg
Solution 2
Solution 3 Rejwanul Reja
Solution 4
Solution 5 Donkixoot