Angular 2 "ng-style" inside "* ngFor" background color changes

I am trying to apply background colors using ng-style . Each line of the list is created using ngFor . Each element 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 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'} ] }, ] 

I don’t know how to apply the color code to the list.

+11
javascript css angular typescript ionic2
source share
3 answers

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

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

Unless, of course, the line in item.bgcolor is a valid css color string:

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

Which is not in your case. You are missing the lead # , and you must change your list of products to this:

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

You can directly apply this css, and alternative lines will have different colors

li {background: green; }

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

+4
source share

for further use by other developers, here is my answer. the function will loop all the colors in each row, ngFor generate 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; } } 
0
source share

All Articles