簡體   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