6đ
In your
canvas ⊠add a #yourId
(example : canvas *ngFor=âlet chart of charts; let i = indexâ id=âcanvas{{i}} #yourIdâ)
Then you can use @ViewChildren(âyourIdâ) myCharts: any; (you canât use myCharts in ngOnInit, only in ngAfterViewInit and after) which will give you your array of charts.
I wonât provide much more detail but you can use whatâs inside your myCharts (use a console.log(myCharts) to see in detail whatâs in there), you can use this to change data and so on.
Hope this helps.
3đ
Here is one of the possible implementations of the previously proposed solution.
I created an array called âchartsâ, which will contain as many elements as charts I want to create. Each element of this array has an identifier and the key where we will place the chart later (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'), {
// ...
}
})
}