1

I am having a challenge trying to create a graph for each mat-card in a *ngFor loop. I am setting the canvas like this:

 <canvas id="coinLineChart{{coin_index}}" width="200" height="150"></canvas> 

then create a variable of the id value like this:

 let chart_id = `coinLineChart` + `${this.coin_index}`.

Then I tried to get the ctx value like this:

 coinLineChart = document.getElementById(chart_id);
 const ctx = coinLineChart.getContext("2d"); 

but coinlLineChart turns out to be null. Can anyone suggest a way to do this? I am using chartjs v3 with Angular 13

MichaelE
  • 757
  • 14
  • 42

1 Answers1

1

you can use a viewChildren or viewChild link to canvas tag to have a list of all canvas on looping side

in the html :

<canvas #canvas width="200" height="150"></canvas> 

you have two situation if your component directly have the *ngFor and the canvas element

in the controller

@ViewChildren('canvas') canvasList: QueryList<ElementRef>

in the function where you need to manipulate canvas

 this.canvasList.toArray().forEach(canvas => {
    const ctx = canvas.getContext("2d");
    //other code on one canvas
});

if your canvas is inside a child component you have the ViewChild directive to manipulate it

in the child controller

@ViewChild('canvas') canvas: ElementRef

in the child function where you need to manipulate canvas

    const ctx = this.canvas.getContext("2d");
    //other code on one canvas
jeremy-denis
  • 6,368
  • 3
  • 18
  • 35
  • This is interesting....but I don't see how it would work? you see my loop (*ngFor) is in my parent who is making multiple calls to . SO how would another loop inside the child work? because each time I access the child I only have one set of data and the index for that data. – MichaelE Jan 04 '22 at 16:32
  • ok if canvas is in child component you also have element viewChild to refer an html componentn in controller ``@ViewChild('canvas') canvas: ElementRef`` – jeremy-denis Jan 04 '22 at 17:08
  • the idea is to not have to do a document.get{Seletcor} but have access to html tag in controller side – jeremy-denis Jan 04 '22 at 17:09
  • i send you a link to another interesting stackoverflow post very near of your situation https://stackoverflow.com/questions/34636435/angular2-what-is-the-best-way-to-get-a-reference-of-a-template-element – jeremy-denis Jan 04 '22 at 17:10
  • i update my reply in consequencies – jeremy-denis Jan 04 '22 at 17:13
  • The above didn't work for me...but it pointed me in the right direction. This worked for me: constructor(private elementRef: ElementRef) { } .....followed by: this.ctx = this.elementRef.nativeElement.querySelector(`#coinLineChart`) – MichaelE Jan 04 '22 at 22:19