在我的 ionic 应用程序中,我试图为每个列表项生成不同的颜色,因为我在 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;
}
Run Code Online (Sandbox Code Playgroud)
在我的 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>
Run Code Online (Sandbox Code Playgroud)
但我收到以下错误,我需要更改以摆脱以下错误
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)
Run Code Online (Sandbox Code Playgroud)
这里发生的事情是,如果您不更改对象引用,而只更改其某些属性,则不会触发 angular 的更改检测。
因此,您对背景颜色的更改仅在下一次更改检测运行中被识别,这不是您想要的。
在开发模式下,Angular 实际上运行了两次更改检测运行来捕获这样的错误。您看到的错误消息就是结果。
组件.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>
Run Code Online (Sandbox Code Playgroud)
组件.ts
getColor() {
const color = this.getRandomColor();
return {
'background-color' : color
}
}
getRandomColor() {
// calc and return random rgba
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
442 次 |
| 最近记录: |