我正在将颜色应用于div元素,并且正在按如下所述循环更改颜色
toogleColor()
{
if(this.color=='blue')
{
this.color="red"
this.fontcolor='white'
return
}else if(this.color=='red'){
this.color='white'
this.fontcolor='black'
return
}else if(this.color=='white'){
this.color='blue'
this.fontcolor='white'
return
}
}
并且我有setStyle()函数,如下所示:
setStyle(){
this.toogleColor()
return {
'background-color':this.color,
'height':'382px'
}
}
在我的组件html中,我绑定了如下样式:
<div [ngStyle]="setStyle()" *ngFor="let element of array1">
但是我没有得到预期的颜色周期,因为setStyle()函数被称为4 *数组中元素的数量
答案 0 :(得分:1)
让我们谈谈代码中的一些错误。
setStyle
是令人困惑的方法,并且同时执行两项操作。实际上,它设置了某些内容,但还返回了一个值。这违反了单一责任原则,也使首先看html的人感到困惑。因此,当我看到[ngStyle]="setStyle()"
时,我会认为这段代码有问题,因为通常setter
不会返回任何内容。 那么,我们该怎么办?
我们需要分开设置颜色和将颜色分为两种不同方法的逻辑。另外,如果可能的话,我们应该避免从html调用方法。
我认为您要尝试的是根据前一个元素的颜色为数组的每个元素分配不同的颜色。因此,您可以执行以下操作
@Component({
selector: 'demo',
template: `
<div [ngStyle]="element.style" *ngFor="let element of array1"></div>
`
})
export class DemoComponent implements OnInit {
array1 = [];
color = 'white';
constructor() { }
ngOnInit() {
// get array from somewhere
// this.array1 =
this.array1.forEach(element => {
const colorConfig = this.getNextColor();
element.style = {
'background-color': colorConfig.color,
'height': '382px',
'color': colorConfig.fontColor
};
});
}
getNextColor() {
let fontColor;
if (this.color === 'blue') {
this.color = 'red';
fontColor = 'white';
} else if (this.color === 'red') {
this.color = 'white';
fontColor = 'black';
} else if (this.color === 'white') {
this.color = 'blue';
fontColor = 'white';
}
return {
color: this.color,
fontColor: fontColor
};
}
}
答案 1 :(得分:0)
对于您来说,最好使用ngClass
而不是ngStyle
,而且我认为您根本不需要使用函数。
样式
.blue {
color:blue;
background-color:red; // many css property
}
.red {
color:red;
...
}
.white {
color:white
...
}
模板
<div [ngClass]="color" *ngFor="let element of array1" >
该类可以具有另一个属性,但是如果您仍然仅更改颜色,则可以使用ngStyle
<div [ngStyle]="{color:color}" *ngFor="let element of array1" >
答案 2 :(得分:0)
是的,自您使用*ngFor
以来,它将多次调用,并且它将创建多个div
元素,并且多个div
将多次调用ngStyle
。
如果您想调用一次,则可以将其包裹起来
<div [ngStyle]="setStyle()">
<ng-container *ngFor="let element of array1">
....
</ng-container>
</div>
如果要在同一div中应用ngStyle并希望重复相同的内容,则应将此setStyle放入某个变量中,以用作-
public style;
ngOnInit(){
this.style = this.setStyle(); //return the styles
}
<div [ngStyle]="style" *ngFor="let element of array1">