Can ngClass use ternary operator in Angular 2?

TypescriptAngular

Typescript Problem Overview


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.

Typescript Solutions


Solution 1 - Typescript

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

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

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

Solution 3 - Typescript

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

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHongbo MiaoView Question on Stackoverflow
Solution 1 - TypescriptMark RajcokView Answer on Stackoverflow
Solution 2 - TypescriptGünter ZöchbauerView Answer on Stackoverflow
Solution 3 - TypescriptRejwanul RejaView Answer on Stackoverflow
Solution 4 - TypescriptsamivicView Answer on Stackoverflow
Solution 5 - TypescriptDonkixootView Answer on Stackoverflow