sridharan
sridharan

Reputation: 2065

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

I am trying to apply background colors using ng-style. Each row of list is generated using ngFor. Each item having separate background colors

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

And the 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'}
    ]
  },
]

Don't know how to apply color code to list.

Upvotes: 13

Views: 20352

Answers (3)

john edgar otom
john edgar otom

Reputation: 153

for future reference for other developers, here's my answer. the function will loop all the colors to each row the ngFor will generate

<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;
    }


  }

Upvotes: 1

Poul Kruijt
Poul Kruijt

Reputation: 71911

You can change the background colour using [style.backgroundColor]:

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

If of course the string in item.bgcolor is a valid css colour string:

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

Which in your case isn't.. You are missing the leading # and you should change your item list to this:

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

Upvotes: 23

dixit thareja
dixit thareja

Reputation: 83

You can directly apply this css and the alternate rows will have different color

li { background: green; }

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

Upvotes: 4

Related Questions