Home > OS >  Chart js error in angular: Canvas is already in use. Chart with ID '0' must be destroyed b
Chart js error in angular: Canvas is already in use. Chart with ID '0' must be destroyed b

Time:05-11

So basically, on div click (jquery), I have a bootstrap modal popup that has a chart. The chart works fine, and the rendering is perfect, the problem comes when I click another div.

Here's my HTML

        <div  id="myModal" tabindex="-1" role="dialog">
            <div >
                <div >
                    <div > hello<i ></i> </div>
                    <div id="chartDiv" *ngIf="chart"><canvas #chart>{{  chart  }}</canvas></div>   
                </div>
            </div>
        </div>

On a separate note, I'm using Chart.register(...registerables) in my constructor. Here goes my TS (just the relevant code):

import { Chart, registerables } from 'chart.js';
export class HomeComponent implements OnInit{
  @ViewChild('chart') canvas: ElementRef;

  chart: any = [];

ngOnInit(): void {   
    $('#myModal').on('hide.bs.modal', function () {
    $(".canvas").remove(); 
    })
    $('#myModal').on('show.bs.modal', function () {
      $("div.chart").append('<canvas #chart>{{chart}}</canvas>');
      $('#chart').trigger('focus')
    })
}

  divClick()
{
 $('#myModal').modal('show'); 
this.chart = this.getChartData()
}

getChartData(): Chart {
this.chart = new Chart(this.canvas.nativeElement.getContext('2d'), {data})
//please don't worry about data its coming from api and it works fine
return this.chart
}

}

This is all just very high level, but I'm happy to include any other code needed. I researched so many articles and ways to fix this error but couldn't find any. If you can point me to a resource where Chart js is implemented using Angular, it'd be helpful. Also, I tried the "destroy" function on this.chart but that doesn't work either. Is there any other way to use this rather than exposing canvas. Just don't know what I'm doing wrong. I even tried removing and re-adding canvas classs through jquery (in onInit) but that doesn't work either. (Chartjs v3.7.0)

CodePudding user response:

You're doing everything right, and you're so close. I believe there's no need to store anything in this.chart. Simply return and render. To fix your multi-instance error, simply add a check for chart existence before rendering.

 divClick()
{
 var chartExist = Chart.getChart("myChart"); // <canvas> id
    if (chartExist != undefined)  
      chartExist.destroy(); 

 $('#myModal').modal('show'); 
 this.getChartData()
}

getChartData(): any {
return new Chart(this.canvas.nativeElement.getContext('2d'), {data})
 
}

In your HTML, simply add id for chart

<canvas id="myChart" #chart>{{  chart  }}</canvas>
  • Related