DOM access in onPageDidEnter


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

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


  // setTimeout( this.drawGraph(null) ,2000 );
    let canvasElement =  document.getElementById("myChart2") ;
    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 ,
            highlight: "#5AD3D1",
            label: "Value 1",
              value:  50 ,
              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.


1 Like

You’re completely right!

Using ngAfterViewInit fixes the problem.