Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change icon color dynamically in Ionic-Angular?

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

like image 253
this.jind Avatar asked Oct 28 '25 08:10

this.jind


1 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
}
like image 103
sebaferreras Avatar answered Oct 29 '25 22:10

sebaferreras



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!