下面是从远程服务器获取数据的 HTML 部分。
<div class="col-md-6 col-xl-4" *ngFor="let material of materials" >
<div class="card widget-statstic-card" >
<div class="card-header">
<div class="card-header-left">
<h3 class="d-inline-block">{{material.Prd_Type}}</h3>
</div>
</div>
<div class="card-block">
<div class="text-left">
<h3 class="d-inline-block">
</h3>
</div>
</div>
</div>
</div>
这是我给出的 TS 函数,该函数从 ts 中定义的颜色数组返回颜色。这里的问题是 *ngFor 循环不断重复,所有颜色都在改变,我不希望它们再次改变。
colors=['red','blue','green'];
materials: any;
randomItem: string;
constructor(public http: HttpService) {
this.http.getMethod('ProductType/get').subscribe((data => {
this.materials = data;
console.log(this.materials);
}));
}
getColor(){
this.randomItem = this.colors[Math.floor(Math.random()*this.colors.length)];
console.log('s',this.randomItem);
return this.randomItem;
}
ngOnInit() {
this.getColor();
}
最佳答案
假设您只想在每次获取数据时随机化颜色,则应该在此时进行随机化:
this.http.getMethod('ProductType/get').subscribe((data => {
this.materials = data.map(material => {
// assumes your data doesn't already have a "color" property
material.color = this.colors[Math.floor(Math.random()*this.colors.length)]
return material
};
console.log(this.materials);
}));
我不知道你在代码中实际在哪里设置背景颜色,但它看起来像这样:
<div class="col-md-6 col-xl-4" *ngFor="let material of materials" [style.background]="material.color">
关于angular - 我正在使用 *ngFor 来迭代卡片布局中的元素。我想随机改变他们的背景颜色有什么办法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51257150/