0

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?

K.Shikha
  • 107
  • 2
  • 14
  • Does this answer your question? [ExpressionChangedAfterItHasBeenCheckedError Explained](https://stackoverflow.com/questions/43375532/expressionchangedafterithasbeencheckederror-explained) – Edric Jul 03 '20 at 04:50
  • @Edric I did look at the post you shared and setInterval() and cdRef.detectChanges() had worked for me. Is there any way to get rid of these hacky methods to bypass the error I'm getting? – K.Shikha Jul 06 '20 at 14:23

1 Answers1

0

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

gsa.interactive
  • 565
  • 2
  • 7
  • The above method bypasses the error, but I'm looking for a way to avoid manually triggering the change detection cycle. – K.Shikha Jul 06 '20 at 16:13