0👍
From your error message, believe that you are trying to add data and re-draw the chart. This will encounter the issue if the chart has been rendered and you are trying to re-draw the chart.
Approach 1: Destroy the chart each time you add the data to the chart and redraw:
// Destroy chart element if existed
if (this.chart)
this.chart.destroy();
// Add data into the `weightLabels` and `monthLabels`
// Create the chart instance
this.chart = new Chart('MyChart', {
type: 'line',
data: {
labels: monthLabels,
datasets: [
{
label: 'Weight',
data: weightLabels,
backgroundColor: 'blue',
},
],
},
options: {
aspectRatio: 2.5,
}
});
Approach 2: Use the update()
API
this.monthLabels.push(/* month value */);
this.weightLabels.push(/* weight value */);
// Or
//this.chart.data.labels?.push(/* month value */);
//this.chart.data.datasets[0].data.push(/* weight value */);
this.chart.update();
Note that you don’t need the Angular interpolation {{ chart }}
inside the <canvas
element. When you create the Chart instance by specifying the element id as the first argument, it will find the matching HTML element and render.
<div class="chart-container" [hidden]="!chart">
<canvas id="MyChart"></canvas>
</div>
Reference: Line Chart Demo with adding data
Source:stackexchange.com