I am facing problem in loading charts in angular 11.the chart is not getting shown when page is loaded but it is getting displayed when we click on some label "student count". I used canvas in html page to display the chart.
I am using chart.js version 2.9.4
<div style="height:250px;">
<canvas id="myChart" width="750" height="250" #mychart>
</canvas>
</div>
my code in typescript file looks something like this
import { Chart } from 'chart.js';
canvas: any;
ctx: any;
@ViewChild('mychart') mychart:any;
ngAfterViewInit() {
this.canvas = this.mychart.nativeElement;
this.ctx = this.canvas.getContext('2d');
new Chart(this.ctx, {
type: 'line',
data: {
datasets: [{
label: 'Students Count',
data: this.row_studnet,//this values received from the backend
backgroundColor: "rgb(115 185 243 / 65%)",
borderColor: "red",
fill: true,
},
],
labels: this.row_feeid//this values received from the backend
},
});
I am not getting the actual issue .please help me to solve this issue.
It's because ngAfterViewInit is called after change detection is completed and the view has already been build. When you click on same label you execute new change detection cycle.
You can try to add this line of code after new Chart(), where cd is ChangeDetectorRef injected in constructor.
setTimeout(() => {
this.cd.markForCheck();
});
which will mark this component as a dirty for change detection.