javascript - 来自组件的 Angular 2 getBoundingClientRect

标签 javascript typescript angular

我有如下组件,它基本上是一个弹出窗口:

import {Component, Input, ViewChild} from 'angular2/core'

declare var $: any;

@Component({
  selector: 'popover',
  template: `
  <div id="temp" [ngStyle]="{'position':'absolute', 'z-index':'10000', 'top': y + 'px', left: x + 'px'}"
       [hidden]="hidden" #temp>
    <ng-content></ng-content>
  </div>
  `
})
export class Popover {

  @ViewChild("temp") temp;

  private hidden: boolean = true;
  private y: number = 0;
  private x: number = 0;

  show(target, shiftx = 0, shifty = 0){
    let position = $(target).offset();
    this.x = position.left + shiftx;
    this.y = position.top + shifty;
    this.hidden = false;

    console.log("#temp", this.temp.nativeElement.getBoundingClientRect()); //all 0s
    console.log("temp id", document.getElementById('temp').getBoundingClientRect()); //all 0s
  }

  hide(){
    this.hidden = true;
  }
}

show() 方法中,我试图获取 getBoundingClientRect() 的结果,但它返回所有属性的 0 但是当我从 Chrome 的控制台输入 document.getElementById("temp").getBoundingClientRect() 我得到了属性中的实际值的正确结果。为什么会有所不同,我该怎么做才能从我的组件中获取实际值?

最佳答案

我没有使用可以多次触发的 setTimeout 或生命周期 Hook ,而是通过设置渲染器来监 window 口加载事件来解决它。

import { OnInit, Renderer2} from '@angular/core';

...

export class MyComponent implements  OnInit {

    constructor(private el: ElementRef, private render: Renderer2) {}

    ngOnInit() {
        this.render.listen('window', 'load', () => {
            const rect = this.el.nativeElement.getBoundingClientRect().top;
        })
    }

}

也许这有助于某人的用例。

关于javascript - 来自组件的 Angular 2 getBoundingClientRect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37881169/

相关文章:

javascript - 有多个模块的名称仅在外壳 React 上不同

javascript - 堆栈跟踪错误仍然显示在我的控制台上

typescript - 防止 typescript 允许未定义的返回

typescript - 是否可以在 Typescript 中声明动态字符串类型

Angular 循环依赖警告

javascript - css api 的 jquery if else 条件

typescript - 在 Next.js 中的高阶身份验证组件中返回附加数据

angular - Kendo UI Tabstrip Onclick 事件

angular - 使用ionic将点击功能绑定(bind)到innerhtml

javascript - 在 IE 中使用 javascript 预填充动态创建的文本框