Issue
I want to have multiple charts which are generated dynamically on one page using Chart.js, Typescript and Angular
On the page:
<canvas *ngFor="let d of data"
style="position:relative, width: 15vh, height: 40vw" #canvases></canvas>
The for-loop just creates the number of charts for which data is available.
In the typescript file:
I thought of using multiple ViewChild statements but that requires knowing how many graphs should be created, which I do not know. I also tried using QueryLists but failed to get them to work because any function I call (toArray, foreach etc.) seems not to be defined.
@ViewChildren('canvases') canvases:QueryList<HTMLCanvasElement>
One individual canvas should be passed to the normal Chart.js function in a loop and then populated with the right data
let newChart = new Chart(individualCanvas, {
type: 'line',
...
})
Has anybody an idea how to get from the generated canvases on the HTML Page to a loop where I can use the individual canvases for the Chart.js instance?
Solution
I have not figured out how the get things to work with a QueryList. But I found a way to avoid them. For that I introduced an additional div on the HTML page with an unique id.
<div #canvases>
<canvas *ngFor="let d of data"
style="position:relative, width: 15vh, height: 40vw"></canvas>
</div>
I then again used a ViewChild but this time binding the div
@ViewChild('canvases') canvases: ElementRef<HTMLElement>
When populating the charts I used a loop and accessed the children of the div which are the individual canvases.
let index = 0
for(let d of this.data){
let individualCanvas = this.canvases.nativeElement.children.item(index)
let newChart = new Chart(individualCanvas, {
type: 'line',
...
})
index++
}
Answered By - primaryDeveloper
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.