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