Phyo
Phyo

Reputation: 27

TypeError: Cannot read property 'nativeElement' of undefined in HTML5 Canvas with Ionic 2

my home.ts looks like this

import { Component,ViewChild,ElementRef} from '@angular/core';

    export class HomePage {
      @ViewChild('canvas') canvasEl : ElementRef;
      private _CANVAS:any;
      private _CONTEXT:any;
    }

    ionViewDidLoad() {
        this._CANVAS = this.canvasEl.nativeElement;
        this._CONTEXT = this._CANVAS.getContext('2d');
      }
    }

this is what I have in home.html

 <canvas #canvas></canvas>

ERROR TypeError: Cannot read property 'nativeElement' of undefined. I keep getting this error and I dont know how to solve. Could someone help me on this Thank you so much.

Upvotes: 0

Views: 1349

Answers (1)

Suraj Rao
Suraj Rao

Reputation: 29614

In order to get the ElementRef, you will have to use angular lifecycle hook ngAfterViewInit instead of the ionViewDidLoad lifecycle hook.

export class HomePage implements AfterViewInit{
    @ViewChild('canvas') canvasEl : ElementRef;
    private _CANVAS:any;
    private _CONTEXT:any;

    ngAfterViewInit() {
        this._CANVAS = this.canvasEl.nativeElement;
        this._CONTEXT = this._CANVAS.getContext('2d');
    }
}

Upvotes: 3

Related Questions