19

I build a tooltip with Angular 5.2.0 and ngrx. When the state updates, the tooltip gets (among other things) an ElementRef to the Element on which it should append (= target). With this target, I can place absolute position the Tooltip:

let rect = state.tooltip.target.nativeElement.getBoundingClientRect();
if (rect) {
  this.position.left = rect.left;
  this.position.top = rect.top;
}

state.tooltip.target is of type ElementRef which the element opening the Tooltip gets via @ViewChild:

@ViewChild('linkWithTooltip') tooltipTarget: ElementRef;

openTooltip() {
    if (this.tooltipOpen) {
      this.tooltipAction.closeTooltip();
    } else {
      this.tooltipAction.openTooltip({
        text: 'foo',
        target: this.tooltipTarget
      });
    }
    this.tooltipOpen = !this.tooltipOpen;
}

with the reference in the template:

<a #linkWithTooltip href="">Lorem</a>

as described here (and in lots of other places).

However, to be able to position the tooltip properly, I have to know the tooltip's size after rendering (for example to center it). What I need is an ElementRef of the Tooltip itself instead of a ViewChild.

How can I get the dimensions of the current component? Can I retrieve them via the Component's ElementRef? And if yes, how do I get the ElementRef?

Florian Gössele
  • 4,376
  • 7
  • 25
  • 49

1 Answers1

28

You can use the dependency injection.

import { Component, ElementRef } from '@angular/core';

@Component({ selector: 'tooltip' })
class TooltipComponent {
   constructor(private ref: ElementRef) {}
}
Tomasz Kula
  • 16,199
  • 2
  • 68
  • 79
  • Thanks, I can access ref.nativeElement.getBoundingClientRect(), but all the values are Zero - I think this is because it is not rendered yet. Is there any way to get around this? I need the height and width of the element, before it is rendered. – Florian Gössele Apr 20 '18 at 14:47
  • Try accessing the `getBoundingClientRect()` in `ngAfterViewInit` lifecycle hook. – Tomasz Kula Apr 20 '18 at 14:50
  • 2
    `ngAfterViewInit` is only called once, the tooltip usually is rendered by user action, so this doesn't work unfortunately... I tried `ngAfterContentChecked` but I get the same result (zero-values). On the other hand, with `ngAfterViewChecked`, I get `ExpressionChangedAfterItHasBeenCheckedError` (which seems logical). I will ask a follow-up question as your answer is definitely right for the question I asked. – Florian Gössele Apr 20 '18 at 15:07