I attempted to create a chart in a parent component using a child component but encountered some difficulties. Here is my code:
Parent component:
@Component({
selector: 'app-tickets',
template: '<canvas id="newChart"></canvas>'
})
export class TicketsComponent implements OnInit {
ngOnInit(): void {
var chart = new Chart('newChart', {
type: 'line',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
datasets:
[
{
label: 'Total De Cada Mes',
data: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
backgroundColor: 'rgba(0, 123, 255, 0.5)',
borderColor: 'rgba(0, 123, 155, 1)',
borderWidth: 2
},
{
label: 'Total de domicilios',
data: [0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0],
backgroundColor: 'rgba(12, 092, 323, 0.5)',
borderColor: 'rgba(12, 092, 323, 1)',
borderWidth: 2,
hidden: true
}
]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
}
It should look like this: https://i.sstatic.net/ybTlx.png
However, when I tried to do the same thing in a child component, I encountered this issue:
Parent component:
@Component({
selector: 'app-tickets',
template: '<app-tickets-chart id="newChart"></app-tickets-chart>'
})
export class TicketsComponent {
}
Child Component (Using the same chart):
@Component({
selector: 'app-tickets-chart',
template: "<canvas [id]='chartId'></canvas>"
})
export class TicketsChartComponent implements AfterViewInit {
@Input()
public chartId: string;
ngAfterViewInit(): void {
if(this.chartId === '') {
throw new Error("Attribute 'chartId' is required.");
}
var chart = new Chart(this.chartId, {
type: 'line',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
datasets:
[
{
label: 'Total De Cada Mes',
data: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
backgroundColor: 'rgba(0, 123, 255, 0.5)',
borderColor: 'rgba(0, 123, 155, 1)',
borderWidth: 2
},
{
label: 'Total de domicilios',
data: [0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0],
backgroundColor: 'rgba(12, 092, 323, 0.5)',
borderColor: 'rgba(12, 092, 323, 1)',
borderWidth: 2,
hidden: true
}
]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
}
And it appears like this:
https://i.sstatic.net/JT33K.png
What should I do to fix this issue?