首页 > 解决方案 > 如何显示多个圆环图

问题描述

我有时想生成多个甜甜圈图,它会是 5 个,有时会是 20 个,具体取决于我必须显示甜甜圈图的数量,我已经尝试了一些级别,我能够在 ngFor 循环中显示引导卡,但不能能够动态地将画布 ID 传递给 ts 文件。

HTML:

       <div class="row">
          <div *ngFor="let dev_data of devices  let i = index" class="col-md-3">
           <div class="card card-body">
             <h6>{{dev_data.device_name}}</h6>
             <canvas  id="canvas{{i}} #yourId" ></canvas>
          </div><br>
         </div>
       </div>

打字稿:

          import { Component, OnInit, ViewChild, ViewChildren } from '@angular/core';
          import { Chart } from 'chart.js'
          import {ElementRef} from '@angular/core';

          @Component({
            selector: 'app-dev',
            styleUrls: ['./dev.component.scss'],
            templateUrl: './dev.component.html'
          })

         export class DevComponent implements OnInit {

          constructor(private elementRef: ElementRef) { }

              ngOnInit() {
                this.createChartsData()
               }

           @ViewChildren('yourId') myCharts: any;

          charts = [];

          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++)
     {

   console.log(this.myCharts)

   let htmlRef = this.elementRef.nativeElement.select(`#yourId`+j);
   var tempChart = new Chart(htmlRef,pieData[j]);
   this.charts.push(tempChart);
  }
 }

         }

我认为错误出现在 **htmlRef ** 变量中,当我使用 console.log(htmlRef) 时,它没有打印任何内容。

然后我打印了 console.log(this.myCharts),我得到了这些数据:

在此处输入图像描述

我现在不卡在哪里,如果有任何帮助,将不胜感激。

标签: angulartypescript

解决方案


 export class DevComponent implements AfterViewInit{
    ngAfterViewInit()
    {
      this.createChartsData()
    }
 }

推荐阅读