Reputation: 13
I am trying to use chart.js to create multiple number of charts according to data that I got from a database.
The documentations said to use the following code in order to create a chart:
@ViewChild('doughnutCanvas') doughnutCanvas;
doughnutChart: any;
createChart(){
this.doughnutChart = new Chart(this.doughnutCanvas.nativeElement, {
type: 'doughnut',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
]
}]
}
});
}
and in the html file:
<ion-card-content>
<canvas #doughnutCanvas></canvas>
</ion-card-content>
The problem is that i don't know in advance how many charts i want to create and want to use ngFor on a dataset that recieved from the database.
How can I do it? the problem is mainly the : @ViewChild('doughnutCanvas') doughnutCanvas; command.
**im using ionic 3 but dont think it is relevant
Upvotes: 1
Views: 2237
Reputation: 8470
I would recommend that you pull out this logic into a reusable chart component and that will take care of it for you. I created a plunkr to show you an example of doing so.
Essentially this allows you to loop over them by rendering a new version of your chart component and passing the necessary data it needs to render like so:
<chart-canvas *ngFor="let chart of charts" [data]="chart"></chart-canvas>
You can then put all of the logic you have shown above in that chart-canvas
component.
Upvotes: 2