首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将数组中的任意颜色赋值时出现ExpressionChangedAfterItHasBeenChecked错误?

将数组中的任意颜色赋值时出现ExpressionChangedAfterItHasBeenChecked错误?
EN

Stack Overflow用户
提问于 2018-05-07 19:48:28
回答 2查看 518关注 0票数 1

我想给数组指定一个随机颜色。它实际上首先工作,但后来我得到一个错误消息:"ExpressionChangedAfterItHasBeenChecked“,我甚至看到它如何在消息到来前一秒钟,芯片的颜色变化非常快。所以它有些作用..。我怎样才能解决这个问题。(我还为芯片的创建添加了代码和函数)我知道我首先必须初始化它。但是我不知道如何做到这一点,所以如果您可以直接在我的代码中编写,那就太好了。我尝试了很多事情,但都没有成功。

HTML

代码语言:javascript
运行
复制
<ion-chip [color]="color[getRandomInt(color.length)]" class="chip" #chip *ngFor="let tag of tagName">

TS

代码语言:javascript
运行
复制
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));
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-05-07 19:58:07

如果在console.log方法中添加一个getRandomInt,您将看到它多次被称为,这不是很好。

相反,我建议为对象分配一次颜色(您还需要将color添加到Tag类中)

像这样的东西

代码语言:javascript
运行
复制
add(): void {
  let id = this.tagName.length + 1;
  this.tagName.push(new Tag({ tag: "tag" + id, color: this.color[this.getRandomInt(this.color.length)] }, ));
}

然后在html中,它将类似于

代码语言:javascript
运行
复制
<ion-chip [color]="tag.color" class="chip" #chip *ngFor="let tag of tagName">
票数 0
EN

Stack Overflow用户

发布于 2018-05-07 19:55:57

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

代码语言:javascript
运行
复制
this.tagName = this.tagName.map((tag) => tag.color =  this.color[this.getRandomInt(this.color.length)]);

然后在HTML中:

代码语言:javascript
运行
复制
<ion-chip [color]="tag.color"
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50221419

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档