Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you get current positional information about an element in Angular2

Tags:

angular

I have the ElementRef of my navbar and I'm trying to find out how close it is to the top of my window so I can make it sticky

<div class="nav-bar" #navBar>

</div>

@ViewChild("navBar")
  navBarElement;

I'm printing out the positions of it's nativeElement in a scroll event but the values seem to be static

@HostListener('window:scroll', ['$event'])
onScroll(event) {
   console.log("offset top", this.navBarElement.nativeElement.offsetTop);
}

How can I track the current position of my element?

like image 662
Josh Elias Avatar asked Nov 29 '16 22:11

Josh Elias


Video Answer


1 Answers

offsetTop is relative to it's place in the document, not relative to the view port.

See How to get an element's top position relative to the browser's window? for how to get the scroll position.

eg. var viewportOffset = el.getBoundingClientRect().top;

like image 169
Fiddles Avatar answered Oct 19 '22 03:10

Fiddles