如何获取组件自己的ElementRef来检索此组件的BoundingClientRect? [英] How to get a Component's own ElementRef for retrieving BoundingClientRect of this Component?
问题描述
我使用Angular 5.2.0和ngrx构建了一个工具提示.状态更新时,工具提示会(除其他事项外)获得应添加元素的ElementRef(=目标).有了这个目标,我可以将工具提示放在绝对位置:
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
的类型为 ElementRef ,打开工具提示的元素通过 @ ViewChild :
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;
}
在模板中带有引用:
<a #linkWithTooltip href="">Lorem</a>
(如此处所述)其他地方).
as described here (and in lots of other places).
但是,为了能够正确放置工具提示,我必须在渲染后知道工具提示的大小(例如将其居中).我需要的是工具提示本身的ElementRef而不是ViewChild.
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.
如何获取当前组件的尺寸?我可以通过组件的ElementRef检索它们吗?如果是的话,如何获得ElementRef?
推荐答案
您可以使用依赖项注入.
You can use the dependency injection.
import { Component, ElementRef } from '@angular/core';
@Component({ selector: 'tooltip' })
class TooltipComponent {
constructor(private ref: ElementRef) {}
}
这篇关于如何获取组件自己的ElementRef来检索此组件的BoundingClientRect?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!