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

101 Views Asked by At

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?

3

There are 3 best solutions below

1
rbkannan On BEST ANSWER

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

0
Philipp Meissner On

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;
}
0
thisdotutkarsh On

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';
    }
}