角度 2 “ng 样式” 中的 “*ngFor” 背景颜色变化

Angular 2 “ng-style” within “*ngFor” background color change

本文关键字:ngFor 背景 颜色 变化 中的 ng 样式 角度      更新时间:2023-09-26

我正在尝试使用ng-style应用背景颜色。列表的每一行都是使用 ngFor 生成的。每个项目都有单独的背景颜色

<ion-item class="category-list" *ngFor="let item of character['items']">
   <ion-avatar item-left>
  <i class="icon" [ngStyle]="{'background-color': item.bgcolor}"><img src="../img/icons/category/{{item.img}}.png"></i>
  </ion-avatar>
    <h2>{{item.category}}</h2>
  </ion-item>

和 Typescript.ts:

 var characters = [
  {
    name: 'Gollum',
    quote: 'Sneaky little hobbitses!',
   items: [
      { bgcolor: 'fb9667', img: 'airTicket', category: 'Air tickets' },
      { bgcolor: '000000', img: 'airTicket', category: 'Beauty/Fitness'},
      { bgcolor: '0b9660', img: 'airTicket', category: 'Bike'}
    ]
  },
]

不知道如何将颜色代码应用于列表。

您可以使用

[style.backgroundColor]更改背景颜色:

<i class="icon" [style.backgroundColor]="item.bgcolor"></i>

当然,如果item.bgcolor中的字符串是有效的 css 颜色字符串:

#FFFFFF white rgb(255,255,255) rgba(255,255,255,1)

在您的情况下不是..您缺少前导#,应将项目列表更改为以下内容:

items: [
      { bgcolor: '#fb9667', img: 'airTicket', category: 'Air tickets' },
      { bgcolor: '#000000', img: 'airTicket', category: 'Beauty/Fitness'},
      { bgcolor: '#0b9660', img: 'airTicket', category: 'Bike'}
]

您可以直接应用此css,交替行将具有不同的颜色

李 { 背景: 绿色; }

li:nth-child(odd) { background: red; }

供其他开发人员将来参考,这是我的答案。该函数会将所有颜色循环到ngFor将生成的每一行

<ion-col [ngStyle]="{'background-color': getColors(i) }" *ngFor="let data of Data;let i = index">
Colors:Array<any> = ["#FFF","#0b9660","#FF0000","#000","#FFF","#ffd11a","#fb9667"];
  getColors(index) {
    let num = this.getnumber(index);
    return this.Colors[num];
  }
  getnumber(data){
    let i = data;
    if(i > this.Colors.length-1){
       i = i - this.Colors.length;
       if(i < this.Colors.length){
        return i;
       }
       else {
        this.getnumber(i);
       }
    }
    else {
      return i;
    }

  }