Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Angular ChartJS 2.9.4 issue updating chart

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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);
        }
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading