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

标签 angular typescript tooltip

我使用 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.targetElementRef 类型打开工具提示的元素通过 @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>

描述here (以及许多其他地方)。

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

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

最佳答案

您可以使用依赖注入(inject)。

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

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

关于angular - 如何获取组件自己的 ElementRef 以检索此组件的 BoundingClientRect?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49905621/

相关文章:

angular - 如何将数据从父组件传递到子组件?

typescript - 将 Jest 与 Typescript 一起使用时的转译

javascript - 如何在 Nest.js 中注入(inject)普通服务/提供者

javascript - 当 CKEditor 破坏 <span> 时,如何在其中包含带有 HTML 的工具提示

javascript - ChartJS 工具提示位置/放置

javascript - ES5 和 ES6 中的 Angular 2 依赖注入(inject)

dependencies - Dartlang 中的依赖问题

angular - ionic slider 隐藏最后一张幻灯片中的下一个按钮 ionic 4

TypeScript:Object.keys 返回字符串 []

wpf - 工具提示与弹出窗口(WPF控件)