简体   繁体   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;

result结果

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

in another component, It works well without any initialization.在另一个组件中,它无需任何初始化即可正常工作。

but I don't know why this component can't work但我不知道为什么这个组件不能工作

The template need to be rendered if you want your ViewChild to not be undefined.如果您希望您的 ViewChild 不是未定义的,则需要呈现模板。 Its all about timing.一切都与时机有关。 You are trying to use something that doesnt exist yet which is why you are having an error.您正在尝试使用尚不存在的东西,这就是您遇到错误的原因。

You need to use a lifecycle hook that angular provide您需要使用 angular 提供的生命周期挂钩

In your case, the view need to be rendered first so I would use ngAfterViewInit() with static: false and ngOnInit() with static: true在您的情况下,需要首先呈现视图,因此我将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