Accepted answer

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.


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).


  <canvas *ngfor="let chart of charts; let i = index" id="mychart{{i}}" #mycharts>{{chart.chart}}</canvas>


 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, i) => {   // for each canvas, save the chart on the charts array 
      this.charts[i].chart = new chart(mycanvas.nativeelement.getcontext('2d'), {
        // ...

Related Query