简体   繁体   中英

ElementRef for ViewChild of ancestor undefined

I'm trying to get the dimensions of a distant ancestor of a clicked element (to determine where the popup should go) and I'm having some trouble. The ElementRef I'm defining comes out as undefined.

The ancestor element:

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

The component that's trying to get the info:

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

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

I've heard of problems with ViewChild and *ngIf, but this component is an ancestor, so everything above it will necessarily have been created already, no?

You can do a setter to listen when the tabContent is available since it depends on a observable.

tabContent: ElementRef;

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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