Angular 在渲染之前,如何获得角度为5的组件的尺寸?

Angular 在渲染之前,如何获得角度为5的组件的尺寸?,angular,typescript,Angular,Typescript,我在Angular 5中实现了一个通用工具提示。为了正确定位(特别是相对于目标元素居中),我需要在渲染工具提示之前获得其宽度和高度 我已经知道如何从中获取组件的尺寸。但是,我需要先设置工具提示的内容(让浏览器确定大小)来计算位置。然后,第二,我想设置位置并添加一个类来显示它 这是我的密码: // tooltip.component.html <div class="popup fade" [ngClass]="tooltip?.isOpen ? 'show' : ''" [styl

我在Angular 5中实现了一个通用工具提示。为了正确定位(特别是相对于目标元素居中),我需要在渲染工具提示之前获得其宽度和高度

我已经知道如何从中获取组件的尺寸。但是,我需要先设置工具提示的内容(让浏览器确定大小)来计算位置。然后,第二,我想设置位置并添加一个类来显示它

这是我的密码:

// tooltip.component.html
<div class="popup fade"
  [ngClass]="tooltip?.isOpen ? 'show' : ''"
  [style.left.px]="calculatedPos?.left"
  [style.top.px]="calculatedPos?.top">
  {{ tooltip?.text }}
</div>

// tooltip.component.ts
export class TooltipComponent {
  public tooltip: any;
  public calculatedPos: TooltipPosition = {
    left: 0,
    top: 0
  }

  constructor(private store: Store<any>, private ref: ElementRef) {
    this.store.subscribe((state) => this.render(state));
  }

  render () {
    let targetRect = this.tooltip.targetEl 
          && this.tooltip.targetEl.nativeElement
          && this.tooltip.targetEl.nativeElement.getBoundingClientRect()
          || null;
    let tooltipRect = this.ref 
          && this.ref.nativeElement
          && this.ref.nativeElement.getBoundingClientRect()
          || null;
    if (targetRect && tooltipRect) { // <-- tooltipRect.height /.width is zero here!
      switch (this.tooltip.placement) {
        case 'right':
          this.calculatedPos = this.calculatePositionRight(targetRect, tooltipRect, this.tooltip.offset)
          break;
          // and so on...
  }
}
//tooltip.component.html
{{工具提示?.text}
//tooltip.component.ts
导出类TooltipComponent{
公共工具提示:任何;
公共计算位置:TooltipPosition={
左:0,,
排名:0
}
构造函数(私有存储:存储,私有引用:ElementRef){
this.store.subscribe((state)=>this.render(state));
}
渲染(){
设targetect=this.tooltip.targetEl
&&this.tooltip.targetEl.nativeElement
&&this.tooltip.targetEl.nativeElement.getBoundingClientRect()的
||无效;
让tooltipRect=this.ref
&&这是国家元素
&&this.ref.nativeElement.getBoundingClientRect()
||无效;

如果(targetRect&&tooltipRect){/要获取元素的维度,则必须等待渲染

如果DOM中没有元素,则无法获取其维度


使用
ngAfterViewInit
,此时视图已初始化。

要获取元素的尺寸,您必须等待它被渲染

如果DOM中没有元素,则无法获取其维度


使用
ngAfterViewInit
,此时视图已初始化。

我认为在
ngAfterViewInit
中设置订阅是没有办法的。要绕过
表达式changedfterthasbeenscheckeederror
,您可以告诉Angular您“知道自己在做什么”。插入
ChangeDetectorRef
,并在
呈现
-方法的末尾放置一个
detectChanges
-调用。

我认为在
ngAfterViewInit
中设置订阅是没有办法的。要绕过
表达式changedfterthasbeenscheckeederror
,您可以告诉Angular“知道你在做什么吗"。插入
ChangeDetectorRef
,并在
render
-方法的末尾放置一个
detectChanges
-调用。

您无法从DOM尚未计算的元素中获取高度。因此,正如您所建议的,让它渲染和隐藏,或者为元素指定一个固定的宽度。请注意,使用
%
设置宽度是错误的也有可能。您无法从DOM尚未计算的元素中获取高度。正如您所建议的,让它呈现和隐藏,或者为元素指定固定宽度。注意:使用
%
设置宽度也是可能的。我使用
ngAfterViewInit
尝试过它,但只调用了一次。不过,工具提示可与diff一起重用每次都有不同的内容。正如我所说的,我也不能使用
ngAfterViewChecked
…我用
ngAfterViewInit
尝试了它,但只调用了一次。但是工具提示每次都会被不同的内容重复使用。正如我所说的,我也不能使用
ngAfterViewChecked
。。。