简体   繁体   中英

Getting Error “ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked” on customizing legends

I'm using Pie charts in my component and want to be able to customize legends. I'm referring to the BaseChart element in my component so that I could access the legendItems property within it. Below is the code which shows how I'm using it

<canvas #sampleBaseChart="base-chart" baseChart [data]="pieChartData" [labels]="pieChartLabels"
    [chartType]="pieChartType" [options]="pieChartOptions" [legend]="pieChartLegend">
</canvas>

And in my component.ts file, I'm referring to it

@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);
    }
  }

And then run a loop over sampleObservable to print the legend items in the form of a list in my component.html file. Something like this:

<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>

When I run my application, it throws an error saying

ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ngForOf: [object Object]'. Current value: 'ngForOf: [object Object],[object Object]'.

I know what the above error means and why it's throwing it. Also, I did try setInterval() and cdRef.detectChanges() methods, but it seems like hacky ways to bypass this error.

Is there any other way to get rid of the above error?

Putting it into a setTimeout() function inside of ngAfterViewInit() will solve your issue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM