首页 > 解决方案 > 自定义图例时出现错误“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 方法。

有没有其他方法可以摆脱上述错误?

标签: angularobservablepie-chartng2-chartsangular-changedetection

解决方案


将其放入 ngAfterViewInit() 内的 setTimeout() 函数将解决您的问题


推荐阅读