How to get a Component's own ElementRef for re

2020-08-26 11:23发布

问题:

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?

回答1:

You can use the dependency injection.

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

@Component({ selector: 'tooltip' })
class TooltipComponent {
   constructor(private ref: ElementRef) {}
}