title: How to get the dimensions of a Component in Angular 5 before rendering it?
body: <p>I'm implementing a generic tooltip in Angular 5. For the proper positioning (especially centering relative to the target element) I need to get the width and height of the tooltip before rendering it.</p>
  
  <p>I already know how to get the dimensions of a component from <a href="https://stackoverflow.com/questions/49905621/how-to-get-a-components-own-elementref-for-retrieving-boundingclientrect-of-thi/4990566">this question</a>. However, I need to set the content of the tooltip first (to let the browser determine the size) to calculate the position. Then, second, I want to set the position and add a class to show it.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>// tooltip.component.html
  &lt;div class="popup fade"
    [ngClass]="tooltip?.isOpen ? 'show' : ''"
    [style.left.px]="calculatedPos?.left"
    [style.top.px]="calculatedPos?.top"&gt;
    {{ tooltip?.text }}
  &lt;/div&gt;
  
  // tooltip.component.ts
  export class TooltipComponent {
    public tooltip: any;
    public calculatedPos: TooltipPosition = {
      left: 0,
      top: 0
    }
  
    constructor(private store: Store&lt;any&gt;, private ref: ElementRef) {
      this.store.subscribe((state) =&gt; this.render(state));
    }
  
    render () {
      let targetRect = this.tooltip.targetEl 
            &amp;&amp; this.tooltip.targetEl.nativeElement
            &amp;&amp; this.tooltip.targetEl.nativeElement.getBoundingClientRect()
            || null;
      let tooltipRect = this.ref 
            &amp;&amp; this.ref.nativeElement
            &amp;&amp; this.ref.nativeElement.getBoundingClientRect()
            || null;
      if (targetRect &amp;&amp; tooltipRect) { // &lt;-- tooltipRect.height /.width is zero here!
        switch (this.tooltip.placement) {
          case 'right':
            this.calculatedPos = this.calculatePositionRight(targetRect, tooltipRect, this.tooltip.offset)
            break;
            // and so on...
    }
  }
  </code></pre>
  
  <p>I tried using lifecycleHooks:</p>
  
  <ul>
  <li><code>ngAfterContentChecked</code> leads to the same result</li>
  <li><code>ngAfterViewChecked</code> gives me (foreseeable) an <code>ExpressionChangedAfterItHasBeenCheckedError</code></li>
  <li><code>ngOnChanges</code> is not called at all when rendering</li>
  </ul>
  
  <p>So: <strong>How can I get the dimensions of the Component before the content is rendered? Or how can I detect the content being rendered and then updating the position?</strong></p>
  
  <p>My next thought would be using a timeout to first let the component render and then setting the position (without the user noticing) - but maybe there is a best practice, which I don't know about yet.</p>