I have a component where I will draw a canvas chart. And when I initialize the component for the first time, everything is ok, but if I leave this component and return to it again, then document.getElementById('myChart'); is null and doesn't draw my chart
ngAfterViewInit() {
Chart.register(...registerables);
this.Chart();
}
private Chart() {
const ctx: any = document.getElementById('myChart');
const myChart = new Chart(ctx.getContext('2d'), { // some shit })
}
I tried to do it differently
const canvas = <HTMLCanvasElement>document.getElementById('myChart');
const ctx = canvas.getContext('2d');
But I didn't quite understand how to solve this error and eventually came to the first option
Argument of type 'CanvasRenderingContext2D | null' is not assignable to parameter of type 'ChartItem'. Type 'null' is not assignable to type 'ChartItem'.
I approached this problem from a different angle. First I used ViewChild and applied ElementRef to it
@ViewChild('myChart') chartRef: ElementRef;
private myChart: Chart;
And be sure to use everything in ngAfterViewInit since it starts working after building the DOM tree
ngAfterViewInit(): void {
this.Chart();
}
this.myChart = new Chart(this.chartRef.nativeElement, {some shit})