Angular 2 getBoundingClientRect from component

Instead of using setTimeout or lifecycle hooks that can be triggered more than once, I solved it with setting the Renderer to watch the window load event.

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;
        })
    }

}

Maybe this helps someone's usecase.


I would use ngAfterContentChecked(). It works perfectly fine for me.

import { AfterContentChecked  } from '@angular/core';

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

I hope it helps. :)


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