Create multiple dynamic charts

前端 未结 2 1999
忘了有多久
忘了有多久 2021-02-06 13:18

i\'m developing a web application - MEAN stack. i\'m trying to use ChartJS doughnut chart but i need it to be completely dynamic - first, the number of charts is dynamic (each c

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-06 14:16

    Here is one of the possible implementations of the previously proposed solution. I created an array called "charts", which will contain as many elements as charts I want to create. Each element of this array has an identifier and the key where we will place the chart later (AfterViewInit).

    HTML:

    {{chart.chart}}

    .TS:

     import {Component, OnInit, Input, AfterViewInit, ViewChildren} from '@angular/core';
     import { Chart } from 'chart.js';
    
     // ...
    
     @ViewChildren('mycharts') allMyCanvas: any;  // Observe #mycharts elements
     charts: any;    // Array to store all my charts
    
     constructor() {
       this.charts = [
        {
          "id": "1",   // Just an identifier
          "chart": []            // The chart itself is going to be saved here
        },
        {
          "id": "2",
          "chart": []
        },
        {
          "id": "3",
          "chart": []
        }
      ]
     }
    
     ngAfterViewInit() {
       let canvasCharts = this.allMyCanvas._results;  // Get array with all canvas
       canvasCharts.map((myCanvas, i) => {   // For each canvas, save the chart on the charts array 
          this.charts[i].chart = new Chart(myCanvas.nativeElement.getContext('2d'), {
            // ...
          }
       })
     }
    

提交回复
热议问题