我想给数组指定一个随机颜色。它实际上首先工作,但后来我得到一个错误消息:"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));
}发布于 2018-05-07 19:58:07
如果在console.log方法中添加一个getRandomInt,您将看到它多次被称为,这不是很好。
相反,我建议为对象分配一次颜色(您还需要将color添加到Tag类中)
像这样的东西
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中,它将类似于
<ion-chip [color]="tag.color" class="chip" #chip *ngFor="let tag of tagName">发布于 2018-05-07 19:55:57
您需要做的是确保只设置了一次颜色,因此需要将方法调用移出模板。相反,你应该这样做:
this.tagName = this.tagName.map((tag) => tag.color = this.color[this.getRandomInt(this.color.length)]);然后在HTML中:
<ion-chip [color]="tag.color"https://stackoverflow.com/questions/50221419
复制相似问题