我有如下组件,它基本上是一个弹出窗口:
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/