I encountered an issue while attempting to dynamically generate charts in my Angular project.
Error: Chart.js failed to create chart due to inability to acquire context from the given item.
export class StudentStudyProgressComponent implements OnInit {
charts = [];
semesters = [1, 2, 3, 4, 5, 6];
constructor(private logic: LogicService) {
}
ngOnInit() {
this.createCharts(this.semesters);
}
private createCharts(semesters: number[]) {
semesters.forEach((semester)=>{
this.charts.push(
new Chart('chartStudyProgress' + semester, {
type: 'doughnut',
data: {
labels: ['Passed', 'Taken', 'Remaining'],
datasets: [
{
data: this.logic.getProgressForSemester(this.student.Curriculum, semester),
borderColor: "#3cba9f",
backgroundColor: [
('#66B266'),
('#FFFF66'),
('#FF7F7F')
]
}
]
},
options: {
title: {
display: true,
text: 'Semester '+semester
},
legend: {
display: false
},
}
})
);
});
}
}
The error seems to be related to dynamically creating the charts in the HTML:
<div class="row" *ngFor="let semester of semesters">
<div class="col-4">
<div [hidden]="!charts">
<canvas id="{{'chartStudyProgress'+semester}}" style="max-width: 30%;">{{ charts[semester] }}</canvas>
</div>
</div>
</div>
If I define the charts statically, it works fine:
<div class="row" >
<div class="col-4">
<div [hidden]="!charts">
<canvas id="chartStudyProgress1" style="max-width: 30%;">{{ charts[1] }}</canvas>
<canvas id="chartStudyProgress2" style="max-width: 30%;">{{ charts[2] }}</canvas>
<canvas id="chartStudyProgress3" style="max-width: 30%;">{{ charts[3] }}</canvas>
<canvas id="chartStudyProgress4" style="max-width: 30%;">{{ charts[4] }}</canvas>
<canvas id="chartStudyProgress5" style="max-width: 30%;">{{ charts[5] }}</canvas>
<canvas id="chartStudyProgress6" style="max-width: 30%;">{{ charts[6] }}</canvas>
</div>
</div>
</div>
Seeking expert assistance to resolve the dynamic chart creation issue.