代码之家  ›  专栏  ›  技术社区  ›  Arad Gonen

创建多个动态图表

  •  6
  • Arad Gonen  · 技术社区  · 7 年前

    我正在开发一个web应用程序-均值堆栈。我正在尝试使用ChartJS甜甜圈图表,但我需要它是完全动态的-首先,图表的数量是动态的(每个图表代表其他东西),所以有时是3个,有时是20个。其次,我希望ti能够访问每个图表,以便实时更改数据。这可能吗?我试图创建一个数组来保存每个图表数据,并使用*ngFor为每个图表创建一个画布元素,但没有成功。

    我的chartjs。组成部分ts:

    import { Component, OnInit } from '@angular/core';
    import { DataService } from '../data.service';
    import { Chart } from 'chart.js';
    import { pieceLabel } from 'chart.piecelabel.js';
    import {ElementRef} from '@angular/core';
    @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){
    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。组成部分html:

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

    在此状态下,ElementRef为null。

    2 回复  |  直到 6 年前
        1
  •  6
  •   Alvin Chipmunk    7 年前

    在您的

    帆布添加#yourId

    (例如:canvas*ngFor=“let chart of charts;let i=index”id=“canvas{{i}}}#yourId”)

    然后可以使用@ViewChildren('yourId')myCharts:any;(您不能在ngOnInit中使用myCharts,只能在ngAfterViewInit和之后使用),这将为您提供图表数组。

    我不会提供更多的细节,但您可以使用myCharts中的内容(使用console.log(myCharts)详细查看其中的内容),您可以使用它来更改数据等等。

    希望这有帮助。

        2
  •  3
  •   Leonardo Kuffo    6 年前

    下面是之前提出的解决方案的可能实现之一。 我创建了一个名为“charts”的数组,它将包含我想要创建的图表所包含的元素。该数组的每个元素都有一个标识符和键,稍后我们将在其中放置图表(AfterViewInit)。

    HTML:

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

    .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'), {
            // ...
          }
       })
     }