lbrahim lbrahim - 1 year ago 415
Javascript Question

Angular 2 getBoundingClientRect from component

I have component like below which is basically a popover:

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

declare var $: any;

selector: 'popover',
template: `
<div id="temp" [ngStyle]="{'position':'absolute', 'z-index':'10000', 'top': y + 'px', left: x + 'px'}"
[hidden]="hidden" #temp>
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 = + shifty;
this.hidden = false;

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

this.hidden = true;

Inside the
method I am trying to get the result of
but its returning
for all properties but when I type in
from Chrome's console I get proper result with actual values in the properties. Why the difference and what can I do to get the actual value from my component?

Answer Source

For some reason, the DOM was not updated right after it was shown so, a setTimeout e.g. 10 did the trick.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download