首页 > 解决方案 > 分配给数组中的随机颜色时出现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));
}

标签: javascripthtmlarraysangulartypescript

解决方案


您需要做的是确保您只设置一次颜色,因此您需要将方法调用移出模板。相反,您应该这样做:

this.tagName = this.tagName.map((tag) => tag.color =  this.color[this.getRandomInt(this.color.length)]);

然后在 HTML 中:

<ion-chip [color]="tag.color"

推荐阅读