【问题标题】:ElementRef is undefined when using @ViewChild使用 @ViewChild 时未定义 ElementRef
【发布时间】:2021-07-10 01:15:07
【问题描述】:
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

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

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

【问题讨论】:

  • 这应该是一个组件吗?
  • 你能提供你的HTML模板的sn-p吗?

标签: angular viewchild elementref


【解决方案1】:

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

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

在您的情况下,需要先渲染视图,因此我将使用 ngAfterViewInit()static: falsengOnInit()static: true

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

【讨论】:

  • 抱歉迟到了。
猜你喜欢
  • 2022-07-19
  • 2023-03-05
  • 1970-01-01
  • 2021-10-04
  • 2019-05-01
  • 2019-01-16
  • 2021-05-01
  • 2017-06-04
  • 2017-03-11
相关资源
最近更新 更多