Search code examples
angularviewchild

Why is ElementRef to Canvas not working here?


I try to load an image into a canvas.

In the template

<canvas #myca id="mycanvas" style="width: 600px; height; 600px; border: 2px red solid;" (mousedown)="mdown ($event)"></canvas>

In the component

@ViewChild('myca', {static: false}) myca: ElementRef <HTMLCanvasElement>;

ngOnInit ()
{
    // ctx by id works!
    //var ctx = (<HTMLCanvasElement> document.getElementById('mycanvas')).getContext('2d'); 

    // ctx by ElementRef fails!
    var ctx = this.myca.nativeElement.getContext('2d'); 

    var img1 = new Image();
    img1.src = "http://any_img_you_want.jpg";

    img1.onload = function () 
    {
        ctx.drawImage (img1, 0, 0);
    }
}

If I get the ctx by the id it works. If I do it by the ElementRef it fails. Whats the problem here?


Solution

  • I found out the reason.

    In newer Angular versions the ViewChild Decorator needs 2nd parameter. With only one I would get a typescript error.

    If I change the static flag from false to true it works.

    No special casting is needed.

    @ViewChild('myca', {static: true}) myca: ElementRef;
    
    ...
    
    var ctx = this.myca.nativeElement.getContext ("2d");