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

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

我的 home.ts 看起来像这样

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');
      }
    }

这是我在 home.html

 <canvas #canvas></canvas>

错误类型错误:无法读取未定义的 属性 'nativeElement'。 我一直收到这个错误,我不知道如何解决。谁能帮我解决这个问题。非常感谢。

为了获得 ElementRef,您必须使用 angular 生命周期挂钩 ngAfterViewInit 而不是 ionViewDidLoad 生命周期挂钩。

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');
    }
}