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

250
Views
How can you have an IF THEN ELSE in Angular with ngStyle?

I am trying to have rows in a table highlight based on a STATUS value. I can get it working with either yellow or no color by doing:

[ngStyle]="{'background-color': cnresult.STATUS === 1 ? 'yellow' : ''}"

How can I add another option where if STATUS === 2 it goes to red?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

You can create a map object in the ts file

colorMap = {
    '1': 'yellow',
    '2': 'red',
}

<div [ngStyle]="{'background-color': colorMap[cnresult.STATUS] || ''}"></div>

By this you can add multiple conditions

over 4 years ago · Santiago Trujillo Report

0

You can do something like this as well,

[ngStyle] = "{'background-color': getBackground(cnresult.STATUS)}"

Then in your component.ts file,

getBackground(status) { (2)
    switch (status) {
      case 1:
        return 'yellow';
      case 2:
        return 'green';
      case 3:
        return 'red';
    }
}
over 4 years ago · Santiago Trujillo Report

0

You can chain multiple ternary operations

[ngStyle]="{'background-color': cnresult.STATUS === 1 ? 'yellow' : cnresult.STATUS === 2 ? 'red' : ''}"

Another, possibly more maintainable option would be to conditionally apply class(es) like so:

<div [class.yellow]="cnresult.STATUS === 1"
     [class.red]="cnresult.STATUS === 2"
></div>

// This belongs in your .css file
.yellow {
  background-color: yellow;
}

.red {
  background-color: red;
}
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!