Chart.js + Angular 5 - уничтожить () несколько динамических диаграмм, созданных с помощью цикла * ngFor - PullRequest
0 голосов
/ 14 сентября 2018

Я создал несколько динамических диаграмм с помощью цикла * ngFor и его работы. Но я хочу уничтожить все графики, прежде чем создавать их во второй раз. Есть ли способ достичь этого. Я хочу уничтожить () графики перед созданием новых, но из-за неизвестного количества графиков каждый раз, когда я могу их достичь.

my 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>

1 Ответ

0 голосов
/ 18 сентября 2018

Решил сам, создав диаграммы непосредственно в массиве диаграмм.

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

и уничтожил диаграммы, перебирая массив диаграмм.

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