javascript - 分配给数组中的随机颜色时出现ExpressionChangedAfterItHasBeenChecked错误?
问题描述
我想分配给数组的随机颜色。它实际上首先起作用,但随后我收到一条错误消息:“ExpressionChangedAfterItHasBeenChecked”我什至在消息出现前一秒看到芯片的颜色变化非常快。所以它有些工作......我该如何解决这个问题。(我还添加了创建芯片的代码和函数)我知道我首先必须初始化它。但我不知道如何实现,所以如果你能直接写在我的代码中就好了。我一直在尝试很多东西,但没有任何效果。
HTML
<ion-chip [color]="color[getRandomInt(color.length)]" class="chip" #chip *ngFor="let tag of tagName">
TS
export class Tag {
color = ["ok", "nice","awesome","danger","white"];
colorSelected = null;
tag: string;
constructor(values: Object = {}) {
Object.assign(this, values);
}
ngAfterViewInit() {
this.colorSelected = this.color[this.getRandomInt(this.color.length)];
}
}
...
color: string [] = ["ok", "nice","awesome","danger","white"]
tagName: Tag[] = [];
...
add(): void {
let id = this.tagName.length + 1;
this.tagName.push(new Tag({ tag: "tag" + id }, ));
}
remove(tag: Tag) {
let id = this.tagName.indexOf(tag);
this.tagName.splice(id, 1);
}
getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
解决方案
您需要做的是确保您只设置一次颜色,因此您需要将方法调用移出模板。相反,您应该这样做:
this.tagName = this.tagName.map((tag) => tag.color = this.color[this.getRandomInt(this.color.length)]);
然后在 HTML 中:
<ion-chip [color]="tag.color"
推荐阅读
- flutter - Flutter 本地通知引发错误
- python - 有没有办法在 Windows 中引用“ipconfig”文件
- amazon-web-services - 带有 EFS 的 AWS 上的 Prometheus Docker - 无写入权限
- python - 确定键盘事件顺序的规则?(Python)
- python - 从 .py 文件导入可视化函数以在 .ipynb 文件中使用
- c# - 通过具有 ef 核心且没有用户定义的表类型的 id 列表查询许多对象
- ruby-on-rails - Rails 5,找不到没有和 ID 的用户。您可以通过表单传递对象吗?
- javascript - Javascript首先从数组中获取数据特定的键
- javascript - 如何使用javascript更改文本的方向
- ms-access - 限制访问表中重复值的输入