I'm facing an issue updating Chart (ver 2.9.4) in Angular 9 , Although I can create new chart instance with new Chart(ctx, config)
but not able to update it. I got ERROR TypeError: chart.update is not a function
Reference: https://www.chartjs.org/docs/2.9.4/developers/updates.html?h=update
Below is my code
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 tried with multiple approaches but no luck so far. Any help on this would be highly appreciated.
Thanks in advance.
CodePudding user response:
I think you need to pass the chart object instead of the ElementRef to the update function of your service and it should work...
updateReport() {
if ( this.dataSource ) {
this.reportService.update(this.chart, this.dataSource);
}
}