2

I have ion-item that will display one of the following Alert, Level 1, Level 2, or Level 3 Emergency.

<ion-item text-wrap *ngFor="let item of levelofEmergency">
    {{item.level}}
</ion-item>

What I am trying to do is assign css according to the text of the level. i.e Alert is grey, Level 1 is green etc..

<ion-item text-wrap *ngFor="let item of statuslevelEmergency">
    <span style="color:red" *ngIf="item.level === 'Alert'">{{item.level}}</span>
</ion-item>

Thanks in advance for any info pointing me in the right direction.

Gregor Albert
  • 819
  • 1
  • 11
  • 23
Thomas Degroot
  • 441
  • 1
  • 12
  • 32
  • You can't use two structural directives like that (*ngFor + *ngIf), you can just add the expresion on the `style` attribute like: `item.level === 'Alert' ? 'red' : ''` – IvanS95 Jan 24 '19 at 21:37

2 Answers2

2

You can bind to the style and then add conditional logic

<ion-item text-wrap *ngFor="let item of statuslevelEmergency">
    <span [style.color]="item.level === 'Alert' ? 'red' : 'green'">{{item.level}}</span>
</ion-item>

See also Style binding from the angular documentation.


If you want a dynamic class (as in found on a style sheet) see this previous answer: Angular: conditional class with *ngClass

Igor
  • 60,821
  • 10
  • 100
  • 175
  • @ThomasDegroot - You never stated what the other colors should be for each level but I was hoping this would give you enough to add them yourself. You can continue to chain as deep as you need or you can move the whole thing into the component and have a method called `getColorForAlert(level: string):string {}` (or something similar) and then call that instead. – Igor Jan 24 '19 at 22:00
2

You can define the level colors in an object having an index signature:

levelColors: { [level: string]: string } = {
  Alert: "grey",
  Level1: "green",
  Level2: "blue",
  Level3: "orange",
  Emergency: "red",
};

and use it like an associative array to set the color attribute with style binding:

<ion-item text-wrap *ngFor="let item of items" [style.color]="levelColors[item.level]">
  <span>{{item.level}}</span>
</ion-item>

See this stackblitz for a demo.


The same result can be obtained with a Map object:

levelColors = new Map<string, string>([
  ["Alert", "grey"],
  ["Level1", "green"],
  ["Level2", "blue"],
  ["Level3", "orange"],
  ["Emergency", "red"],
]);

using a slightly different syntax in the template:

<ion-item text-wrap *ngFor="let item of items" [style.color]="levelColors.get(item.level)">
  <span>{{item.level}}</span>
</ion-item>

See this stackblitz for a demo.

ConnorsFan
  • 70,558
  • 13
  • 122
  • 146