angular - 自定义图例时出现错误“ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked”
问题描述
我在我的组件中使用饼图并希望能够自定义图例。我指的是组件中的 BaseChart 元素,以便我可以访问其中的 legendItems 属性。下面是显示我如何使用它的代码
<canvas #sampleBaseChart="base-chart" baseChart [data]="pieChartData" [labels]="pieChartLabels"
[chartType]="pieChartType" [options]="pieChartOptions" [legend]="pieChartLegend">
</canvas>
在我的 component.ts 文件中,我指的是它
@ViewChild('sampleBaseChart') sampleBaseChart;
sampleObservable = new BehaviorSubject([]);
ngAfterViewInit(): void {
this.legendData = this.baseChart.chart.generateLegend();
if (this.sampleBaseChart.chart.legend.legendItems) {
this.sampleChartLegendItems = this.sampleBaseChart.chart.legend.legendItems;
this.sampleObservable.next(this.sampleChartLegendItems);
}
}
然后在 sampleObservable 上运行一个循环,以在我的 component.html 文件中以列表的形式打印图例项。像这样的东西:
<ul class="custom-legend-list">
<li *ngFor="let item of sampleObservable | async;let i = index" class="custom-legend-item">
<span class="slice-color" [ngStyle]="{'background-color': item.fillStyle}"></span>
<span class="slice-title">{{ item.text }}</span>
</li>
</ul>
当我运行我的应用程序时,它会抛出一个错误说
ERROR 错误:ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改。以前的值:'ngForOf: [object Object]'。当前值:'ngForOf:[object Object],[object Object]'。
我知道上面的错误是什么意思以及为什么抛出它。此外,我确实尝试了setInterval()和cdRef.detectChanges()方法,但这似乎是绕过此错误的 hacky 方法。
有没有其他方法可以摆脱上述错误?
解决方案
将其放入 ngAfterViewInit() 内的 setTimeout() 函数将解决您的问题
推荐阅读
- r - 将纬度/经度转换为正确的格式
- algorithm - 算法问题,合并整数列表的成本
- java - 从霓虹灯迁移到 2019 12 后如何在启动时修复 Eclipse 框架事件错误
- python - “不是无”在这里有什么用吗?
- unity3d - Unity3d:如何从命令行指定场景构建?
- python - 如何使用 Beautiful Soup 从某个 url 下的所有子 url 获取信息?
- java - 如何将 log4j.properties 文件转换为 log4j2.xml 或 log4j2.properties 文件
- amp-html - 如何获取使用 AMP 分页的数据
- javascript - 在第 7 个子实时数据库“转换”为 json 数组之后
- python - train.py 文件中没有名为“tensorflow.contrib”的模块