我的 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/