我有如下所示的组件,它基本上是一个弹出:
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()时,我会得到属性中的实际值的适当结果。为什么有这种区别,我能做些什么才能从组件中获得实际的值?
发布于 2016-06-20 05:51:05
由于某些原因,DOM在显示出来后没有立即更新,例如,一个setTimeout (例如10 )就成功了。
发布于 2018-01-15 13:33:44
我没有使用可以多次触发的setTimeout或生命周期挂钩,而是通过设置Renderer来查看窗口加载事件来解决这个问题。
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;
})
}
}也许这能帮上忙。
发布于 2017-07-07 18:52:00
我将使用ngAfterContentChecked()。对我来说很好。
import { AfterContentChecked } from '@angular/core';
export class ModelComponent implements AfterContentChecked {
ngAfterContentChecked() {
//your code
}
}希望能帮上忙。:)
https://stackoverflow.com/questions/37881169
复制相似问题