如何解决使用@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;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。