javascript - 类型错误 : Cannot read property 'nativeElement' of undefined in HTML5 Canvas with Ionic 2

标签 javascript ionic2 html5-canvas

我的 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 生命周期钩子(Hook) ngAfterViewInit 而不是 ionViewDidLoad 生命周期钩子(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');
    }
}

关于javascript - 类型错误 : Cannot read property 'nativeElement' of undefined in HTML5 Canvas with Ionic 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51321878/

相关文章:

javascript - 在页面中指定 ionic 组件 css 类

html - XSLT:如何将 Javascript 代码从 xml 复制到 html,修改其中的某些行

javascript - 裁剪不规则形状的图像并拉伸(stretch)它

javascript - 使用 Canvas 元素通过 JavaScript 调整图像大小

javascript - 在 spring mvc 应用程序中链接资源的正确方法

javascript - 正则表达式封装

javascript - 检查(从书签)是否加载了页面?

javascript - 如何在页面加载时使用 javascript/jquery 滑动/打开特定菜单项?

javascript - 处理 http 调用的响应 : filter is not a function

cordova - 错误 : Failed to transpile program - ionic2