在 ng for 循环 angular 4 中更改背景颜色时出错

error in changing the background color in ng for loop angular 4

在我的离子应用程序中,我试图为每个列表项生成不同的颜色,为此我在 comp.ts

中编写了以下函数
getRandomColor() {
     var trans = '0.5'; // 50% transparency
     var color = 'rgba(';
     for (var i = 0; i < 3; i++) {
       color += Math.floor(Math.random() * 255) + ',';
      }
     color += trans + ')'; // add the transparency
      return color;
      }

在我的 html 文件中,我这样称呼它

     <ion-content>
            <ion-list class="quoteList" *ngIf = "data" no-lines>
              <button ion-item *ngFor="let item of data" [ngStyle]="
                   {'backgroundColor': getRandomColor() }"
                          (click)="quoteSelected(item)">
                  {{ item.name }}
                 </button>  
             </ion-list>
     </ion-content>

但我收到以下错误,我需要更改以消除以下错误

Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'backgroundColor: background-color:rgba(106,186,144,0.5)'. Current value: 'backgroundColor: background-color:rgba(200,98,210,0.5)'.
at viewDebugError (http://localhost:8100/build/vendor.js:10149:32)

这里发生的事情是,如果您不更改对象引用,而只更改其某些属性,则不会触发 angular 的更改检测。

因此您对 background-color 的更改仅在下一次更改检测 运行 中被识别,这不是您想要的。

在开发模式下 Angular 实际上 运行 有两个变更检测 运行 来捕获像这样的错误。而您看到的错误消息就是其结果。

component.html

<ion-content>
  <ion-list class="quoteList" *ngIf = "data" no-lines>
    <button ion-item *ngFor="let item of data" [ngStyle]="getColor()" (click)="quoteSelected(item)">
       {{ item.name }}
    </button>  
  </ion-list>
</ion-content>

component.ts

getColor() {
  const color = this.getRandomColor();

  return {
    'background-color' : color
  }
}


getRandomColor() {
   // calc and return random rgba
}

如果您提前设置颜色,应该可以避免显示该消息。类似于:

  colors=[];
  ...
  for (let i = 0; i < 2; i++) {
      this.colors.push(this.getRandomColor());
    }
  }

DEMO