【发布时间】:2020-05-05 10:29:04
【问题描述】:
有时我想生成多个甜甜圈图,它会是 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),我得到了这些数据:
我现在没有卡在哪里,如果有任何帮助,将不胜感激。
【问题讨论】:
-
一个“ViewChildren”将在 ngAfterViewInit 下“可见”,而不是在 ngOnInit 中
-
@Eliseo 我没有得到你的答案,你能解释一下..brefily
-
实现 AfterViewInit 并将代码 ngOnInit 放在 ngAfterViewInit 中
标签: angular typescript