繁体   English   中英

未定义祖先的 ViewChild 的 ElementRef

[英]ElementRef for ViewChild of ancestor undefined

我正在尝试获取单击元素的远祖的尺寸(以确定弹出窗口应该去哪里),但遇到了一些问题。 我定义的 ElementRef 显示为未定义。

祖先元素:

<div class="tab-content" #tabContent *ngIf="registry$ | async as registry">
  //subcomponent
</div>

试图获取信息的组件:

export class StatDisplayComponent implements AfterViewInit {
  @ViewChild('tabContent') tabContentElement: ElementRef;

  constructor() { }
  
  ngAfterViewInit(){
    console.log(this.tabContentElement)
  }

我听说过 ViewChild 和 *ngIf 的问题,但是这个组件是一个祖先,所以它上面的所有东西都必须已经创建了,不是吗?

当 tabContent 可用时,你可以做一个 setter 来监听,因为它依赖于一个 observable。

tabContent: ElementRef;

@ViewChild("tabContent", { static: false, read: ElementRef }) set _tabContentElement(tabContent: ElementRef) {

    if (tabContent) {
      this.tabContent = tabContent;
    }
  }

暂无
暂无

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

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