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

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.

Leave a comment