angular 中的图表 js 错误:Canvas 已在使用中。必须先销毁 ID 为“0”的图表,然后才能重新使用 canvas。使固定?

Chart js error in angular: Canvas is already in use. Chart with ID '0' must be destroyed before the canvas can be reused. Fix?

所以基本上,在 div 上单击 (jquery),我有一个 bootstrap 模式弹出窗口,其中有一个图表。图表工作正常,渲染也很完美,当我点击另一个 div.

时,问题就来了

这是我的 HTML

        <div class="modal fade" id="myModal" tabindex="-1" role="dialog">
            <div class="modal-dialog">
                <div class="card">
                    <div class="text-right cross"> hello<i class="fa fa-times"></i> </div>
                    <div id="chartDiv" *ngIf="chart"><canvas #chart>{{  chart  }}</canvas></div>   
                </div>
            </div>
        </div>

另外,我在构造函数中使用了 Chart.register(...registerables)。这是我的 TS(只是相关代码):

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
}

}

这只是非常高级的内容,但我很乐意包含任何其他需要的代码。我研究了很多文章和修复此错误的方法,但找不到。如果您能为我指出使用 Angular 实现 Chart js 的资源,那将会很有帮助。 另外,我在 this.chart 上尝试了“销毁”功能,但这也不起作用。除了暴露 canvas 之外,还有其他方法可以使用它吗?只是不知道我做错了什么。我什至尝试通过 jquery(在 onInit 中)删除并重新添加 canvas 类,但这也不起作用。 (Chartjs v3.7.0)

你做的一切都对,而且你非常接近。我相信没有必要在 this.chart 中存储任何东西。只需 return 并渲染。要修复您的 multi-instance 错误,只需在呈现之前添加图表是否存在的检查。

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

在您的 HTML 中,只需添加图表 ID

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