【问题标题】:Angular 2 “ng-style” within “*ngFor” background color change“*ngFor”背景颜色变化中的Angular 2“ng-style”
【发布时间】:2016-11-15 18:11:51
【问题描述】:

我正在尝试使用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'}
    ]
  },
]

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

【问题讨论】:

    标签: javascript css typescript angular ionic2


    【解决方案1】:

    您可以使用[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'}
    ]
    

    【讨论】:

    • 它不工作..它需要在这个前面添加#标签吗?
    • 我就是这么说的.. :)
    【解决方案2】:

    你可以直接应用这个 css 并且交替的行会有不同的颜色

    li { 背景:绿色; }

    li:nth-child(odd) { 背景:红色; }

    【讨论】:

    • 我需要每行不同的颜色,超过 50 行
    【解决方案3】:

    供其他开发人员将来参考,这是我的答案。 该函数会将所有颜色循环到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;
        }
    
    
      }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-06
      • 1970-01-01
      • 1970-01-01
      • 2017-04-14
      • 2021-10-02
      • 2014-09-14
      • 2011-11-30
      • 1970-01-01
      相关资源
      最近更新 更多