[英]change dynamic color - ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked
I have json like:我有 json 像:
export class NestedTag {
code: number;
name: string;
parent: number;
children?: NestedTag[];
}
I want to display each tag and its children in a circle in a different color.我想以不同颜色将每个标签及其子项显示在一个圆圈中。
To do this: There is an array of colors:为此:有一个 colors 数组:
colorTagsList= new Array<string>('#FFA200','#26BCC0','#475363','#6BB745','#0D7BAF');
Function for obtaining the current color: Function 获取当前颜色:
getColor( ):string{
if(this.colorTagsList[this.indexColor] ===undefined){
this.indexColor=0;
}
return this.colorTagsList[this.indexColor++];
}
my HTML code:我的 HTML 代码:
<div >
<span *ngFor="let tags of nestedRefTags; Last as lastTag" >{{lastTag}}
<button class="tag" [ngStyle]="{'background-color': getColor()}">
<span > {{ tags.parent.name}}</span>
<span *ngIf="tags.children.length>0" > -</span>
<span *ngFor="let tag of tags.children ; last as isLast">
<span> {{tag.name}}</span>
<span *ngIf="!isLast"> | </span>
</span>
</button>
</span>
</div>
But I get an error:但我得到一个错误:
core.js:6237 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: '#FFA200'. Current value: '#0D7BAF'.
at throwErrorIfNoChangesMode (core.js:8156)
at bindingUpdated (core.js:20051)
at pureFunction1Internal (core.js:36876)
at Module.ɵɵpureFunction1 (core.js:36656)
at ViewItemComponent_span_29_Template (view-item.component.html:45)
at executeTemplate (core.js:12098)
at refreshView (core.js:11945)
at refreshDynamicEmbeddedViews (core.js:13335)
at refreshView (core.js:11968)
at refreshComponent (core.js:13410)
What should I do?我应该怎么办?
getColor()
is a function and will be reevaluated everytime a change is detected. getColor()
是一个 function 并且每次检测到更改时都会重新评估。 Every time you change the value of this.indexColor
this function is reeveluated and a new color returned.每次更改
this.indexColor
的值时,都会重新调整此 function 并返回新颜色。 At the end of the reevaluation you will end up with all your tags having the same color.在重新评估结束时,您最终会得到所有标签的颜色相同。
Below solution removes the getColor()
and assigns each tag a color property that is then used to set the color下面的解决方案删除
getColor()
并为每个标签分配一个颜色属性,然后用于设置颜色
colorTagsList = new Array<string>(
"#FFA200",
"#26BCC0"
...
);
nestedRefTags = [ ... ].map((item, i) => ({...item, color: this.colorTagsList[i]}) );
and in the html并在 html
<div>
<span *ngFor="let tags of nestedRefTags; last as lastTag"
>{{lastTag}}
<button class="tag" [ngStyle]="{'background-color': tags.color }">
<span> {{ tags.parent.name}}</span>
<span *ngIf="tags.children.length > 0"> -</span>
<span *ngFor="let tag of tags.children ; last as isLast">
<span> {{tag.name}}</span>
<span *ngIf="!isLast"> | </span>
</span>
</button>
</span>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.