【发布时间】:2019-11-15 17:43:47
【问题描述】:
我正在尝试在一页上输入Angular 多个图表。我看到了一个带有ViewChildren 的示例:
const baseConfig: Chart.ChartConfiguration = {
type: 'pie',
options: {
responsive: true,
}
};
@ViewChildren('chart', { read: ElementRef }) chartElementRefs: QueryList<ElementRef>;
chartData: Chart.ChartData[] = [
{
labels: ['1500', '1600', '1700', '1750', '1800', '1850', '1900', '1950', '1999', '2050'],
datasets: [{
data: [86, 378, 106, 306, 507, 111, 133, 221, 783, 5000],
borderColor: 'red',
fill: false
}]
},
{
labels: ['1500', '1600', '1700', '1750', '1800', '1850', '1900', '1950', '1999', '2050'],
datasets: [{
data: [86, 378, 106, 306, 507, 111, 133, 221, 783, 5000].reverse(),
borderColor: 'blue',
fill: false
}]
}
];
ngAfterViewInit() {
this.charts = this.chartElementRefs.map((chartElementRef, index) => {
const config = Object.assign({}, baseConfig, { data: this.chartData[index]
});
console.log(chartElementRef);
return new Chart(chartElementRef.nativeElement, config);
});
}
我试图用一种方法来实现它:
@ViewChildren('chart', { read: ElementRef }) chartElementRefs: QueryList<ElementRef>;
chartData: Chart.ChartData[] = []
createChartData(){
var arrayChart: any = []
console.log('number of charts', this.numberOfCharts);
for (var i = 0; i < this.numberOfCharts; i++){
var pie = {
labels: ["Disks", "Mgmt", "Hardware", "FC", "Vols&Pols"],
datasets: [{
data: [20, 20, 20, 20, 20],
backgroundColor: ["#008000", "#008000", "#008000", "#008000", "#008000"]
}]
}
arrayChart.push(pie);
}
this.chartData= arrayChart;
this.charts = this.chartElementRefs.map((chartElementRef, index) => {
const config = Object.assign({}, baseConfig, { data: this.chartData[index]
});
console.log(chartElementRef);
return new Chart(chartElementRef.nativeElement, config);
});
}
HTML:
<div *ngFor="let chart of chartData">
<canvas #chart></canvas>
</div>
并在ngAfterViewInit() 中调用了该方法,但这不起作用……它只显示空的地方。但是,如果我像示例一样这样做,那么它将显示 2 个饼图。有谁知道为什么?
编辑
我想在订阅服务的方法中做到这一点
【问题讨论】:
标签: javascript angular typescript visual-studio chart.js