Using Multiple canvas in same page

Hello

Does anyone have an example for using multiple canvas in the same page?

I have something like this in html:

<div style="height: 138px" *ngFor="let item of listItems; let i = index">
    <canvas #pieCanvas id="pieCanvas{{i}}" style="width: 100px !important; height: 100px !important"></canvas>
  </div>

in .ts:

@ViewChild(“pieCanvas”) pieCanvas: ElementRef;

for (var j = 0; j < chartcount; j++)
{

let htmlRef = document.getElementById(‘pieCanvas’+j);
this.pieCanvas = new Chart(htmlRef, piechartdata);

}

Getting always null is not an object (evaluating ‘item.length’) error.

With only one chart it works perfect, but there I use sth. like

this.barCanvas = new Chart(this.barCanvas.nativeElement…

I googled, but couldn’t find a solution.

Thanks for your help!

Cheers

If you don’t get any better answers, I would isolate each canvas into a separate component, which should eliminate a host of problems with attempting to access things being generated inside that ngFor loop.

Hello,
with your ngFor you create a bunch of canvas with the same #pieCanvas and different id’s.
@ViewChild fetch the first hit and only the first hit of his query to #pieCanvas
In your loop you fetch each canvas by id and create every i a new chart, that is assigned/overwrittes again and again the same #pieCanvas

Maybe you are looking for @ViewChildren to get references to all canvases with #pieCanvas.
Take a look here https://www.concretepage.com/angular/angular-viewchildren#ContentChildren

Best regards, anna-liebt

Hello

Thank you for your help. Via @Viewchildren I found the solution.

See I have found the solution…finally!!!

In html:

<canvas #barCanvas id="barCanvaslist{{i}}"></canvas>

Then in ts: @ViewChildren(‘barCanvas’) Canvaslist: QueryList; charts: any;

and afterwards:

this.Canvaslist.changes.subscribe(c => 
{ c.toArray().forEach(item => 
  { 
    this.Canvaslist = new Chart(item.nativeElement, pieData[j]);
    j = j+1;
  }) 
});

this does the trick

2 Likes

Can you help me ? plz