MichaelE
MichaelE

Reputation: 767

how to use chartjs graph in a *ngFor loop

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

Upvotes: 1

Views: 1083

Answers (1)

jeremy-denis
jeremy-denis

Reputation: 6878

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

Upvotes: 1

Related Questions