多少次应用ngStyle

时间:2018-11-15 07:38:46

标签: css angular html5 angular6

我正在将颜色应用于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 *数组中元素的数量

3 个答案:

答案 0 :(得分:1)

让我们谈谈代码中的一些错误。

  1. setStyle是令人困惑的方法,并且同时执行两项操作。实际上,它设置了某些内容,但还返回了一个值。这违反了单一责任原则,也使首先看html的人感到困惑。因此,当我看到[ngStyle]="setStyle()"时,我会认为这段代码有问题,因为通常setter不会返回任何内容。
  2. 您从html调用了一个方法,这将导致无法预测的行为,例如您现在所拥有的行为。这是因为Angular将此概念称为更改检测。如果您还没有听说过,则应该阅读一下。简而言之,每当触发事件(用户单击,xhr请求等)时,Angular就会遍历您的html和您的组件以检测是否发生了更改。这样做时,如果您的html中有一个方法,则angular将调用它来获取结果值以进行一些检查,如果被调用的方法没有做任何超级复杂的事情并且很快完成,则在某些情况下可能是可以的。但是,对于您的情况,它会执行某些操作,并且会更改颜色。

那么,我们该怎么办?

我们需要分开设置颜色和将颜色分为两种不同方法的逻辑。另外,如果可能的话,我们应该避免从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" >

stackblitz demo

答案 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">