问题描述
@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() {
}
}
<div style="text-align:center">
<canvas #myCanvas id="myCanvas">
</canvas>
</div>
*控制台中的错误如下:-“ core.js:4197错误TypeError:无法读取StlAppComponent.mySubmit(stl-app.component.ts:59)和StlAppComponent.ngOnChanges处未定义的属性'nativeElement' (stl-app.component.ts:51)“
如何避免出现“ nativeElement”问题?这个错误的原因是什么?*
解决方法
Angular的生命周期挂钩'__name__'
在呈现组件模板之前首先执行,这意味着您的@ViewChild myCanvas仍未由Angular初始化,它仅在初始化视图后才有一个值。
以下是有关Angular Components Lifecycle Hooks顺序的文档:https://angular.io/guide/lifecycle-hooks#lifecycle-event-sequence
一种快速的解决方法是用这样的值检查来包围Submit()调用
api.lua
如果希望在视图初始化后立即执行某些操作(并且在ngOnChanges
中获得一个值),则可以使用 ngOnChanges(changes: SimpleChanges) {
if(this.myCanvas) {
this.mySubmit();
}
}
钩子