在.ts文件中,我有:-
@Component({
selector: 'stl-app',
templateUrl: './stl-app.component.html',
styleUrls: ['./stl-app.component.scss']
})
export class ImlStlAppComponent implements OnChanges {
@Input()
filename: string;
@Input()
colorname: any;
@Input()
perspective: number;
private scene: Scene;
private camera: PerspectiveCamera;
private renderer: WebGLRenderer;
@ViewChild("myCanvas") myCanvas: any;
constructor(private render: Renderer2,private sanitizer: DomSanitizer) {
}
ngOnInit(): void {
//add listener for the resize of the window - will resize the renderer to fit the window
let global = this.render.listen('window', 'resize', (evt) => {
this.onWindowResize();
})
}
ngOnChanges(changes: SimpleChanges) {
this.mySubmit();
}
mySubmit() {
//renderer
this.renderer = new WebGLRenderer({ alpha: true, canvas: this.myCanvas.nativeElement});
this.renderer.setSize(this.width, this.height);
//Set scene, camera,lights etc
})
//request animation
this.animate(this.controls);
}
//will resize the renderer and the camera to the right size of the window
onWindowResize() {
}
}
在.html文件中,我有:-
<div style="text-align:center">
<canvas #myCanvas id="myCanvas">
</canvas>
</div>
*控制台中的错误如下:;core.js:4197错误类型错误:无法读取StlAppComponent.mySubmit(stl app.component.ts:59(和StlAppComponent.ngOnChanges(stl apps.components:51(上未定义的属性"nativeElement";
如何避免这个"nativeElement"问题?这个错误背后的原因是什么?*
Angular的生命周期挂钩ngOnChanges
在组件模板渲染之前首先执行,这意味着您的@ViewChild myCanvas仍然没有被Angular初始化,它只有在视图初始化后才会有值。
以下是关于角度组件生命周期挂钩顺序的文档:https://angular.io/guide/lifecycle-hooks#lifecycle-事件序列
一个快速的解决方法是通过像这样的值检查来包围submit((调用
ngOnChanges(changes: SimpleChanges) {
if(this.myCanvas) {
this.mySubmit();
}
}
如果您希望在视图初始化后立即执行某些操作,则可以使用ngAfterViewInit()
挂钩(并且您在myCanvas
中获得一个值(