How to change icon color dynamically in Ionic-Angular?

Viewed 2364

I have a list of chats, and I like to change the color of ion-icon depending on the status of a chat(from attribute chat.status):

<ion-list  *ngFor = "let chat of chats">
 <ion-item>
   <ion-icon name="ellipse-outline" slot ="end"  color ="primary"></ion-icon>
      <ion-label>
        <h2> {{chat.username}} </h2>
      </ion-label>
 </ion-item>
</ion-list>

The icon color should be red when chat.status is A and green when chat.status is B. How can I do this?

Thanks a lot

3 Answers

You can use the ternary operator to set the color in that way:

[color]="chat.status === 'A' ? 'danger' : 'success'"

I'm using Ionic's danger as the red color, and Ionic's success color as the green color but you can add your own colors if you want.

Another option could be to add a class to the ion-icon element and set the color using CSS (like explained in https://ionicons.com/usage):

<ion-icon 
  slot ="end" 
  name="ellipse-outline" 
  [class.red]="chat.status === 'A'"
  [class.green]="chat.status === 'B'"
></ion-icon>

And then in your scss file:

ion-icon.red {
  color: red; // your red color
}

ion-icon.green {
  color: green; // your green color
}

One way to do it is using style binding in your template:

<ion-icon name="ellipse-outline" slot ="end" 
[style.color]="chat.status === 'A' ? 'red' : chat.status === 'B' ? 'green' : 'black'"></ion-icon>

Another way is using a directive in your template:

<ion-icon name="ellipse-outline" slot ="end" [ngStyle]="colorIcon()"></ion-icon>

You can control the styles from your component returning an object:

public colorIcon(): Object {
    if (chat.status === 'A') {
        return {color: 'red'}
    } else if (chat.status === 'B') {
        return {color: 'green'}
   } else {
        return {}
   }
}

You can also directly provide hex color using style binding

<!-- mycolor = "#123456" -->
<ion-icon [style.color]="mycolor" name="square"></ion-icon>
Related