Troubleshooting problem with chart update in Angular using ChartJS version 2.9.4

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.

Answer №1

To resolve the issue, consider passing the chart object to the update function in your service instead of the ElementRef.

updateData() {
        if ( this.dataSource ) {
          this.chartService.modify(this.chart, this.dataSource);
        }
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to store data in the localStorage directly from a server

I'm facing an issue - how can I store data in localStorage that was received from the server? Should I use localStorage.setItem for this purpose? And how do I handle storing an array in localStorage? Or am I missing something here? import { HttpCli ...

Guide to accessing Angular app on a mobile device within the same network

I'm facing an issue with my Angular App when trying to access it on mobile within the same network. I've attempted running ng serve --host <my IP> or ng serve --host 0.0.0.0 and it works well. However, the problem arises because the applica ...

Tips for concealing the delete button within the main content area and displaying it in the subsequent "add" pop-up window upon clicking the "add" button in Angular

I have a card with add and delete buttons. I want only the add button to show initially, and when clicked, a new card should open with both add and delete buttons. Everything is working as expected except I can't figure out how to hide the delete butt ...

The result should display the top 5 application names based on the count property found within the ImageDetails object

data = { "ImageDetails": [ { "application": "unknownApp, "count": 107757, }, { "application": "app6", "count": 1900, }, { & ...

Triggering the MouseLeave event in Chart.js with Angular

I encountered a situation with my Angular component code and need some guidance. Below is the code in question: Angular component html <canvas myChart> [dataset] = "dataVariable" [labels] = "labelVariable" (chartHover) = "chartHover($event ...

There seems to be an issue with the map files when using the "ng serve" command with Angular

After upgrading from Angular 9 to Angular 13 with an Ivy compiler, I noticed that by default, AOT is not set to true. Surprisingly, when I run ng build with source maps on, everything functions correctly and I can set breakpoints that are hit accurately. H ...

Tips for wrapping text in a column within material-ui's DataGrid

Struggling to apply word wrap to my column header title in DataGrid from material-ui. I've attempted using sx and style with no success. I even tried this: const StyledDataGridtwo = styled(DataGrid)<DataGridProps>(({ theme }) => ({ root: { ...

Tips for finding the displayRows paragraph within the MUI table pagination, nestled between the preceding and succeeding page buttons

Incorporating a Material-UI table pagination component into my React application, I am striving to position the text that indicates the current range of rows between the two action buttons (previous and next). <TablePagination ...

Converting text data into JSON format using JavaScript

When working with my application, I am loading text data from a text file: The contents of this txt file are as follows: console.log(myData): ### Comment 1 ## Comment two dataone=1 datatwo=2 ## Comment N dataThree=3 I am looking to convert this data to ...

Tips for clearing the form after submission or canceling with formik

const CustomizedForm: React.FunctionComponent<Props> = (props) => { const formErrorSchema = yup.object({ name: yup.string().required("Name is required"), }); const formValidationLogic = (fieldName) => { return { ...

Move the page to the beginning of the vertical stepper upon clicking the "next" button

I am currently working on optimizing a lengthy form to enhance user experience. To illustrate my point, I have come across a simplified example of the code I am dealing with which can be found here. My primary goal is to ensure that when a user proceeds t ...

Tips on adjusting the rotation speed of an Angular Material progress-spinner

For my web project, I have incorporated a material progress spinner. However, I am finding that it rotates at a very slow speed. Is there anyone who knows how to increase the rotation speed of this spinner? ...

Is there a method for establishing a connection to oracledb using TypeScript ES6 class and module?

My goal is to implement an Oracle connection using Typescript ES6 Class module. I have successfully installed the @types/oracledb package and oracledb package, with the Jasmin framework used in my project. Below is the code I have implemented: import * ...

Utilizing TypeScript's generic constraints for multiple primitive data types

Consider the following function: myFunc(object: string | null): string | null {} The desired behavior for this function is to return type string when the object parameter is of type string, and return type string | null when the object parameter is of ty ...

Is it possible to include a script in the header using Angular's platform-browser?

Is it possible to dynamically add a script to an angular project using the "@angular/platform-browser" library? If so, what is the process for accomplishing this task? ...

Steps for incorporating moment.js into an Angular 2 project

Having trouble importing moment.js into my angular2 application despite following various guides and solutions provided. Even though the package is present in my IDE (Visual Studio) and the moment.d.ts file is easily found, I keep encountering errors when ...

Utilizing Reactjs and typescript to dynamically set width and height properties of a div element using randomly generated variables

I am attempting to set a randomly generated variable as the width and height of a div. I have successfully written a function that generates a random size, but encounter an error when trying to assign it to the style attribute. My objective is to create a ...

What is the correct way to globally set the Angular locale?

I am attempting to configure French as the global locale for an Angular application. According to the documentation, this is what I have added to my app.module.ts: import { registerLocaleData } from '@angular/common' import localeFr from ' ...

The height of the ion-textarea in Ionic-angular reduces

I've been working on a project using the ionic-angular framework. I've encountered an issue where the height of the ion-textarea is sometimes decreased to 0px. The code for the textarea looks like this: <ion-textarea class="translated&quo ...

Provide the context for a template within a dynamically generated component

I have been working on creating a component similar to a tooltip control, but I am facing an issue. The current setup only supports simple text in the ng-template, and when attempting to pass a more complex template with bindings, it breaks. To address thi ...