My goal is to display multiple Charts in a single page using Angular
. I came across an Example that uses 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);
});
}
I attempted to achieve the same functionality within a method:
@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>
Even after calling the method in ngAfterViewInit()
, the Charts are not being displayed. When following the example structure, it works perfectly and displays two Pie Charts. Any insights on why this could be happening?
EDIT
The objective is to implement this functionality within a method to subscribe from a Service.