Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

942
Views
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.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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?

over 4 years ago · Santiago Trujillo Report

0

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

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

over 4 years ago · Santiago Trujillo Report

0

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!