How to get a Component's own ElementRef for retrieving BoundingClientRect of this Component?

放肆的年华 提交于 2019-12-07 07:03:26

问题


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) {}
}


来源:https://stackoverflow.com/questions/49905621/how-to-get-a-components-own-elementref-for-retrieving-boundingclientrect-of-thi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!