Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

html - 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...