Search code examples
angulartypescriptcanvaschart.jsdestroy

Canvas is already in use even after using destroy() when leave the page and comeback to add data


I am getting the error Canvas is already in use. Chart with ID ' ' must be destroyed before the canvas with ID 'MyChart' can be reused. The error appears 4/5 times for each particular id in the console.I have already added . If I stay in the page and add data, doesn't show the error but if I go to another page and come back to this component to add data, the error appears .

if (this.chart){
        this.chart.destroy(); 
        }  
this.chart = new Chart('MyChart', {
    type: 'line',
     data: {
     labels: monthLabels,
     datasets: [
      {
        label: 'Weight',
        data: weightLabels,
        backgroundColor: 'blue',
      },
    ],
  },
  options: {
    aspectRatio: 2.5,        
  },
}); 

Solution

  • Add the following code instead of the if condition

    var exists = Chart.getChart('MyChart');
    exists?.destroy();