【问题标题】:How to change icon color dynamically in Ionic-Angular?如何在 Ionic-Angular 中动态更改图标颜色?
【发布时间】:2020-12-30 22:21:15
【问题描述】:

我有一个聊天列表,我喜欢根据聊天状态更改 ion-icon 的颜色(来自属性 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>

chat.status 为 A 时图标颜色应为红色,chat.status 为 B 时为绿色。我该怎么做?

非常感谢

【问题讨论】:

    标签: html css angular ionic-framework


    【解决方案1】:

    您可以使用三元运算符以这种方式设置颜色:

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

    我使用 Ionic 的 danger 作为红色,使用 Ionic 的 success 作为绿色,但您可以根据需要添加自己的颜色。

    另一种选择是向ion-icon 元素添加一个类并使用CSS 设置颜色(如https://ionicons.com/usage 中所述):

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

    然后在你的 scss 文件中:

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

    【讨论】:

      【解决方案2】:

      一种方法是在模板中使用style binding

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

      另一种方法是在模板中使用directive

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

      您可以从返回对象的组件中控制样式:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-04-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多