Tengo un componente donde dibujaré un gráfico de lienzo. Y cuando inicializo el componente por primera vez, todo está bien, pero si dejo este componente y vuelvo a él nuevamente, entonces document.getElementById('myChart'); es nulo y no dibuja mi gráfico
ngAfterViewInit() { Chart.register(...registerables); this.Chart(); } private Chart() { const ctx: any = document.getElementById('myChart'); const myChart = new Chart(ctx.getContext('2d'), { // some shit }) }Traté de hacerlo diferente
const canvas = <HTMLCanvasElement>document.getElementById('myChart'); const ctx = canvas.getContext('2d');Pero no entendí muy bien cómo resolver este error y finalmente llegué a la primera opción.
Argument of type 'CanvasRenderingContext2D | null' is not assignable to parameter of type 'ChartItem'. Type 'null' is not assignable to type 'ChartItem'.Me acerqué a este problema desde un ángulo diferente. Primero usé ViewChild y le apliqué ElementRef
@ViewChild('myChart') chartRef: ElementRef; private myChart: Chart;Y asegúrese de usar todo en ngAfterViewInit ya que comienza a funcionar después de construir el árbol DOM
ngAfterViewInit(): void { this.Chart(); } this.myChart = new Chart(this.chartRef.nativeElement, {some shit})