使用@ViewChild 时未定义 ElementRef

问题描述

import {Component,ElementRef,HostBinding,ViewChild} from '@angular/core';
export class MainPage {
  constructor(
    el: ElementRef
  ) {
    this.contentElement = el.nativeElement;
  }

  contentElement = null;

@ViewChild('wrapper',{ static: true }) wrapper: ElementRef;

this.size = this.wrapper.nativeElement.clientWidth - 36;

结果

ERROR TypeError: Cannot read property 'nativeElement' of undefined
console.log(this.wrapper);
=>undefined

在另一个组件中,无需任何初始化即可正常工作。

但是我不知道为什么这个组件不能工作

解决方法

如果您希望 ViewChild 不被定义,则需要渲染模板。一切都与时机有关。您正在尝试使用尚不存在的内容,这就是您遇到错误的原因。

您需要使用 angular 提供的 lifecycle 钩子

在您的情况下,视图需要首先呈现,因此我将 ngAfterViewInit()static: false 一起使用,将 ngOnInit()static: true 一起使用

ngAfterViewInit(): void {
    this.size = this.wrapper.nativeElement.clientWidth - 36;
}