Kamran Mushtaq
Kamran Mushtaq

Reputation: 183

Chart.js + Angular 5 - Destroy() multiple dynamic charts created through *ngFor loop

I have created multiple dynamic charts by *ngFor loop and its working. But I want to destroy all the charts before creating them second time. is there any way to achieve it. I want to destroy() the charts before creating new one but due to unknown number of charts every time i am enable to achieve it.

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

and this is the chartjs.component.html:

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

Upvotes: 1

Views: 2013

Answers (1)

Kamran Mushtaq
Kamran Mushtaq

Reputation: 183

Solved myself by creating charts directly into charts array.

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

and destroyed the charts by iterating on charts array.

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

Upvotes: 1

Related Questions