gpt4 book ai didi

javascript - Chart.js + Angular 5 - Destroy() 通过 *ngFor 循环创建的多个动态图表

转载 作者:行者123 更新时间:2023-11-30 20:11:45 24 4
gpt4 key购买 nike

我通过 *ngFor 循环及其工作创建了多个动态图表。但我想在第二次创建图表之前销毁所有图表。有什么办法可以实现它。我想在创建新图表之前销毁()图表,但由于每次我能够实现它时图表数量未知。

我的 chartjs.component.ts:

import { Component, OnInit, ElementRef } from '@angular/core';

import { Chart } from 'chart.js';
import { pieceLabel } from 'chart.piecelabel.js';

import { DataService } from '../data.service';

@Component({
selector: 'app-chartjs',
templateUrl: './chartjs.component.html',
styleUrls: ['./chartjs.component.css']
})
export class ChartjsComponent implements OnInit {
constructor(private _dataService: DataService, private elementRef: ElementRef) {
}

jsons: any;
NumberOfSystems: Number;
charts = [];

ngOnInit() {
this._dataService.getData().subscribe(data => {
this.jsons = data
this.NumberOfSystems = this.jsons.data[0][1].systems.length
this.createChartsData()
});
}

createChartsData() {
var array = [];

for (var i = 0; i < this.NumberOfSystems; i++) {
var pie = {
type: 'doughnut',
data: {
labels: ["Disks", "Mgmt", "Hardware", "FC", "Vols&Pols"],
datasets: [{
backgroundColor: ["#008000", "#008000", "#008000", "#008000", "#008000"],
data: [20, 20, 20, 20, 20]
}]
},
options: {
title: { display: false },
animations: true,
tooltips: { enabled: true },
legend: { display: true }
}
};
array.push(pie);
}

this.createCharts(array);
}

createCharts(pieData) {
if (canvas0) {
this.canvas0.destroy();
}

for (var j = 0; j < this.NumberOfSystems; j++) {
let htmlRef = this.elementRef.nativeElement.select(`canvas` + j);
console.log(htmlRef);
var tempChart = new Chart(htmlRef, pieData[j]);
this.charts.push(tempChart);
}
}
}

这是 chartjs.component.html:

<div>
<canvas *ngFor="let chart of charts; let i = index" id="canvas{{i}}"></canvas>
</div>

最佳答案

通过直接在图表数组中创建图表来解决我自己的问题。

 var ctx4: any = document.getElementById(`chart` + i);
this.charts.push(new Chart(ctx4, bar));

并通过迭代图表数组来销毁图表。

if (this.charts) {
this.charts.forEach(p => {
p.destroy();
});
}

关于javascript - Chart.js + Angular 5 - Destroy() 通过 *ngFor 循环创建的多个动态图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52331060/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com