Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

245
Views
The elementId is null after the second time the component has been initialized

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'.
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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})
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!