首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角2 getBoundingClientRect组分

角2 getBoundingClientRect组分
EN

Stack Overflow用户
提问于 2016-06-17 12:05:53
回答 4查看 22.2K关注 0票数 12

我有如下所示的组件,它基本上是一个弹出:

代码语言:javascript
复制
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()时,我会得到属性中的实际值的适当结果。为什么有这种区别,我能做些什么才能从组件中获得实际的值?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2016-06-20 05:51:05

由于某些原因,DOM在显示出来后没有立即更新,例如,一个setTimeout (例如10 )就成功了。

票数 3
EN

Stack Overflow用户

发布于 2018-01-15 13:33:44

我没有使用可以多次触发的setTimeout或生命周期挂钩,而是通过设置Renderer来查看窗口加载事件来解决这个问题。

代码语言:javascript
复制
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;
        })
    }

}

也许这能帮上忙。

票数 12
EN

Stack Overflow用户

发布于 2017-07-07 18:52:00

我将使用ngAfterContentChecked()。对我来说很好。

代码语言:javascript
复制
import { AfterContentChecked  } from '@angular/core';

export class ModelComponent implements AfterContentChecked  {
   ngAfterContentChecked() {
        //your code
    }
}

希望能帮上忙。:)

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37881169

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档