1

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?

jugglervr
  • 315
  • 1
  • 14
  • * first, the visibility of that element depends on the observable so angular's `ngOninit`(ViewChild static = true) or `ngAfterViewInit`(ViewChild static = false) has probably passed before the observable emits. You can also look at the 2nd argument of `ViewChild` to see what i mean. https://stackoverflow.com/a/56359612/9732932 – The.Wolfgang.Grimmer Oct 18 '20 at 05:26

1 Answers1

0

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.Wolfgang.Grimmer
  • 1,172
  • 2
  • 9
  • 32