【问题标题】:How to change the color of a text/item/css inside a *ngFor?如何更改 *ngFor 中的文本/项目/css 的颜色?
【发布时间】:2020-09-17 15:56:35
【问题描述】:

我有一个使用数组的项目创建器,它使用 *ngFor="let 选项创建项目列表。

我想根据它们的值更改这些项目的颜色,但我似乎做不到。

tankItAwnserArray = ['Yes','Yes','Option','NO'];
 <ion-item *ngFor="let option of tankItAwnserArray">
        <ion-item> Move Damage:  {{option}}</ion-item>
      </ion-item>

我希望“是”值为绿色,“选项”为橙色,“否”为红色。

我尝试了很多东西,但我无法让它发挥作用。

谁能帮帮我?

【问题讨论】:

    标签: javascript html css angular colors


    【解决方案1】:
        interface Colors {
        yes: string; 
        option: string;
        no: string;
        }
    
        const colors: Colors = {
        yes: '#336699',
        option: '#223366',
        no: '#223366'
        }
    
    Push the colors from your JSON directly into the inline styles like...
    
    <span [ngStyle]="{'color': colors[option.toLowercase()]}">{{option}}</span>
    

    【讨论】:

      【解决方案2】:

      您可以将条件 CSS 类与 *ngClass 一起使用


      Component.HTML

      <ion-item *ngFor="let option of tankItAwnserArray">
          <ion-item>
              Move Damage:  
              <span [ngClass]="{'green-class': option === 'Yes', 'orange-class': option === 'Option', 'red-class': option === 'No' }">{{option}}</span>
          </ion-item>
      </ion-item>
      

      Component.CSS

      .green-class { color: green; }
      .orange-class { color: orange; }
      .red-class { color: red; }
      

      【讨论】:

      • 它在 css 部分显示“选择器匹配未知元素绿色类”
      • CSS文件的CSS类名前应该有一个点(.),我编辑了答案。
      • 我理解代码,但它不起作用。文本仍然是白色/默认
      猜你喜欢
      • 2020-05-31
      • 2011-01-13
      • 2020-09-04
      • 2017-11-21
      • 2019-09-21
      • 1970-01-01
      • 2012-07-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多