Utilizing a chart
component for generating new charts:
import { AfterViewInit, Component, ElementRef, Input, ViewChild } from '@angular/core';
import Chart, { ChartConfiguration } from 'chart.js/auto';
@Component({
selector: 'app-chart',
templateUrl: './chart.component.html',
styleUrls: ['./chart.component.scss']
})
export class ChartComponent implements AfterViewInit {
@ViewChild('chart') chartEl: ElementRef<HTMLCanvasElement>
@Input() chart: any;
constructor() { }
ngAfterViewInit(): void {
new Chart(this.chartEl.nativeElement, this.createChartConfig(this.chart))
}
private createChartConfig(chart): ChartConfiguration<"line">{
return {
type: chart?.type,
data: chart?.data,
options: chart?.options,
}
}
}
In order to specify a type for my @Input() chart: any;
, I have installed the corresponding type definition, although its necessity in chart.js v3 is uncertain:
"chart.js": "^3.8.0",
"@types/chart.js": "^2.9.37",
Lastly, here is a dataset for the charts:
export const charts: Array<any> = [
{
type: 'line',
data: {
labels: [
'January',
'February',
'March',
'April',
'May',
'June',
],
datasets: [
{
label: 'My First dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 2, 20, 30, 45],
},
{
label: 'My Second dataset',
backgroundColor: 'rgb(123, 24, 201)',
borderColor: 'rgb(100, 99, 132)',
data: [5, 60, 15, 8, 20, 45, 45],
}
]
},
},
{
type: 'bar',
data: {
labels: [
'January',
'February',
'March',
'April',
'May',
'June',
],
datasets: [
{
label: 'Dataset 1',
data: [5, 60, 15, 8, 20, 45],
backgroundColor: 'red',
},
{
label: 'Dataset 2',
data: [2, 30, 215, 18, 33, 90],
backgroundColor: 'green'
},
{
label: 'Dataset 3',
data: [3, 0, 25, 23, 25, 95],
backgroundColor: 'purple',
},
]
},
options: {
scales: {
x: {
stacked: true,
},
y: {
stacked: true
}
}
}
},
]