user17449555
user17449555

Reputation: 213

Failed to create chart: can't acquire context from the given item Angular

I am using Chart.js in Angular 15 , the console displays the following. 2 errors -

  1. vendor.js:209527 Failed to create chart: can't acquire context from the given item .
  2. Canvas is already in use. Chart with ID '2' must be destroyed before the canvas with ID 'MyChart' can be reused . I have input fields that add data to the chart. When added I see this error. Even though the app runs but I guess need to fix this error.Is it possible without adding ng2-charts library?

html

     <div class="chart-container" [hidden]="!chart">
        <canvas  id="MyChart" >{{chart}}</canvas>
    </div>

ts

 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,        
      },

Upvotes: 0

Views: 165

Answers (1)

Yong Shun
Yong Shun

Reputation: 51195

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>

Demo @ StackBlitz

Reference: Line Chart Demo with adding data

Upvotes: 0

Related Questions