如何获取组件自己的 ElementRef 以检索此组件的 BoundingClientRect?

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

我用 Angular 5.2.0 和 ngrx 构建了一个工具提示。当状态更新时,工具提示(除其他事项外)获得一个 ElementRef 到它应该追加(=目标)的元素。有了这个目标,我可以放置工具提示的绝对位置:

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

state.tooltip.target 的类型是 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;
}

在模板中引用:

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

如所述(以及许多其他地方)。

但是,为了能够正确定位工具提示,我必须知道渲染后工具提示的大小(例如将其居中)。我需要的是工具提示本身的 ElementRef 而不是 ViewChild。

如何获取当前组件的尺寸?我可以通过组件的 ElementRef 检索它们吗?如果是,我如何获得 ElementRef?

您可以使用依赖注入。

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

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