所以基本上,在 div click (jquery) 上,我有一個帶有圖表的引導模式彈出視窗。圖表作業正常,渲染完美,當我單擊另一個 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 上的“銷毀”功能,但這也不起作用。有沒有其他方法可以使用它而不是暴露畫布。只是不知道我做錯了什么。我什至嘗試通過 jquery(在 onInit 中)洗掉和重新添加畫布類,但這也不起作用。(Chartjs v3.7.0)
uj5u.com熱心網友回復:
你做的一切都是對的,你是如此接近。我相信沒有必要在 this.chart 中存盤任何內容。只需回傳并渲染。要修復您的多實體錯誤,只需在渲染前添加圖表是否存在檢查。
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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/472739.html
標籤:javascript jQuery 有角度的 打字稿 图表.js
