I am currently experiencing difficulties with updating a Chart (version 2.9.4) in Angular 9+. While I can create a new chart instance using new Chart(ctx, config)
, I am unable to update it and receive an error message stating ERROR TypeError: chart.update is not a function
For more information, please refer to: https://www.chartjs.org/docs/2.9.4/developers/updates.html?h=update
Below is the code snippet:
ReportComponent.html
<canvas #chart style="width: 100%; height: 480px;">{{chart}}</canvas>
<button (click)="generateReport()">Generate</button>
<button (click)="updateReport()">Update</button>
ReportComponent.ts
export class ReportDashboardComponent implements OnInit, AfterViewInit {
@ViewChild('chart', { static: false }) chartRef: ElementRef;
chart: Chart;
dataSource: any;
constructor(
private reportService: ReportService,
) {}
generateReport() {
if ( this.dataSource ) {
this.chart = this.reportService.init(this.chartRef, this.dataSource);
}
}
updateReport() {
if ( this.dataSource ) {
this.reportService.update(this.chartRef, this.dataSource);
}
}
}
ReportService.ts
import { Chart, ChartConfiguration, ChartOptions, ChartData } from 'chart.js';
export class ReportService {
chart: Chart;
constructor() { }
init(chartRef: ElementRef, data: UniChartData): Chart {
const ctx = chartRef.nativeElement.getContext('2d');
const config = this.getConfig(data);
return new Chart(ctx, config);
}
update(chart: Chart, data: any): void {
if (!chart) { return; }
chart.config = this.getConfig(data);
chart.update();
}
}
I've attempted various solutions but have not had success so far. Any assistance on this matter would be greatly appreciated.
Thank you for your help.