Chartjs-Angular 10 – Chart.js to draw chart in Array with convas id on runtime

0👍

The problem is that Chart.js cannot find a canvas with an id that matches the specified chartCanvas at the time when you create the chart.

new Chart(chartCanvas, {
  ...

Due to the *ngIf and *ngFor directives in the HTML template, the canvas elements are included in the DOM only once the certificateData.setPressureResults array contains some elements. The Angular automatic change detection mechanism is normally responsible to keep the DOM synchronized with the data contained in the component class.

To solve your problem, you need to manually trigger change detection after updatating certificateData.setPressureResults but before creating the chart(s). This can be done through a call of ChangeDetectorRef.detectChanges().

Therefore, the code of your component class would have to be changed as follows:

constructor(private cdr: ChangeDetectorRef, ...) {
  ...
}

// trigger change detection wherever it fits
this.cdr.detectChanges();

Leave a comment