角度 2 “ng 样式” 中的 “*ngFor” 背景颜色变化
Angular 2 “ng-style” within “*ngFor” background color change
我正在尝试使用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;
}
}
相关文章:
- 使用JS如何动态更改显示的html文件中的文本背景颜色
- 可以在这里为背景图像设置滤镜吗
- 如何使用jquery更改html中的背景颜色
- 使用 js 将背景图像设置为 HTML
- 使用带括号的图像URL作为jQuery的背景
- 如何使用css动画/javascript使具有背景图像的元素出现
- 循环浏览多个身体背景图像
- 将淡入淡出添加到“我的身体背景滑块”
- 浮动图像左作为背景-css
- Fullpage.js-视频+背景在同一部分
- 背景图像顶部的滚动图像不移动
- 在pdfmake中嵌入背景图像
- PhoneGap选项卡栏自定义字体,背景图案
- Javascript对象类在单击时打开窗口进行颜色选择,并在更改时替换对象背景颜色
- 不同页面背景的body标记上的角度ng样式
- 修复选择菜单时的背景图像
- 导航菜单-悬停时的背景行为怪异
- JS幻灯片与CSS背景颜色变化
- 使用css()设置背景图像;不起作用
- 角度 2 “ng 样式” 中的 “*ngFor” 背景颜色变化