'Angular 13, Chart.js, ng2-chart Update data from API dynamically

I'm trying to dynamically update chart data from API. I'm using angular 13 and chart.Js 3.7.1.

I didn't found any straightforward example from their documentation.

I found this example on web as well, Still that is not working here. Is there any clear example/tutorial?



Solution 1:[1]

Being able to update the data of a chart is an essential task, so both Chart.js and ng2-charts (which is basically an Angular wrapper of Chart.js) have posted explicit examples:

  • Updating data on Chart.js

    function addData(chart, label, data) {
        chart.data.labels.push(label);
        chart.data.datasets.forEach((dataset) => {
            dataset.data.push(data);
        });
        chart.update();
    }
    
  • Updating data on ng2-charts (check, for instance, the randomize() function)

    public randomize(): void {
        for (let i = 0; i < this.lineChartData.datasets.length; i++) {
            for (let j = 0; j < this.lineChartData.datasets[i].data.length; j++) {
                this.lineChartData.datasets[i].data[j] = LineChartComponent.generateNumber(i);
            }
        }
        this.chart?.update();
    }
    

On both cases, to update the data you will need to modify the data array. Keep in mind, you must explicitly call the update() function right after data update.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 George Kamtziridis