繁体   English   中英

使用 @ViewChild 时未定义 ElementRef

[英]ElementRef is undefined when using @ViewChild

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 提供的生命周期挂钩

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM