DOM access in onPageDidEnter

Hi,

I’m having problems accessing a Canvas element in onPageDidEnter().

Trying to create a chart with http://chartjs.org/ it onPageDidEnter() fails and I suspect that is because DOM is not fully created.

onPageDidEnter()
  {

  // setTimeout( this.drawGraph(null) ,2000 );
    let canvasElement =  document.getElementById("myChart2") ;
    console.log(canvasElement);
    var canvas : HTMLCanvasElement = <HTMLCanvasElement> canvasElement;
    console.log("canvas " + canvas.height);
    var ctx : CanvasRenderingContext2D   =  canvas.getContext("2d");
    console.log("ctx null? " + (ctx == null ));

    let data = [
        {
            value:  50 ,
            color:"#46BFBD",
            highlight: "#5AD3D1",
            label: "Value 1",
          },
          {
              value:  50 ,
              color:"#F7464A",
              highlight: "#FF5A5E",
              label: "Value 2",
            }
        ];

        let myDoughnutChart = new Chart(ctx).Doughnut(data,{});
  }

Uncaught IndexSizeError: Failed to execute 'arc' on 'CanvasRenderingContext2D': The radius provided (-0.5) is negative.

Doing this after a button push generates 0 errors.

Anyone knows what the problem is?

This bug seems to imply that your suspicions are correct- if the DOM is not fully loaded, the radius can’t be calculated correctly.

You can try one of these angular lifecycle states. I’m not familiar enough with them to say with certainty where the onPageDidEnter state fits in with all of the Angular ones though, so you may still have the same problem.

ngAfterViewInit
ngAfterViewChecked

1 Like

You’re completely right!

Using ngAfterViewInit fixes the problem.

Thanks!