如何避免 angular 中的 TypeError?

How to avoid TypeError in angular?

在我的 .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 处未定义的 属性 'nativeElement'(stl-app.component.ts:59) 和 StlAppComponent.ngOnChanges (stl-app.component.ts:51)"

如何避免这个 'nativeElement' 问题?这个错误背后的原因是什么?*

Angular的生命周期钩子ngOnChanges在组件模板渲染之前先被执行,也就是说你的@ViewChild myCanvas还没有被Angular初始化,它只会在视图初始化后有一个值。

这是关于 Angular 组件生命周期挂钩顺序的文档:https://angular.io/guide/lifecycle-hooks#lifecycle-event-sequence

一个快速的解决方法是通过像这样的值检查来包围 submit() 调用

      ngOnChanges(changes: SimpleChanges) {
        if(this.myCanvas) {
          this.mySubmit();
        }
      }

如果您希望在视图初始化后立即执行某些操作,您可以使用 ngAfterViewInit() 挂钩(并且您会在 myCanvas 中获得一个值)