1

I'm using @ViewChild to access a native DOM element in my template. I want to figure out where in the viewport this element is.

this.myElement.nativeElement.???

I believe I need to get a few data points here to figure this out.

I can get the height of the viewport with:

window.innerHeight

But I'm stumped on how to find the position of myElement in relation to said viewport with Angular.

DA.
  • 38,399
  • 48
  • 141
  • 208
  • What about [Intersection Observer](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API)? – bigless Jul 18 '18 at 00:09
  • Possible duplicate of [Retrieve the position (X,Y) of an HTML element](https://stackoverflow.com/questions/442404/retrieve-the-position-x-y-of-an-html-element) – ConnorsFan Jul 18 '18 at 00:39

1 Answers1

3

Use getBoundingClientRect

constructor(private ele: ElementRef<HTMLElement>)
{

}

// scrolls an element into view if it's too close to the top of the screen
scrollIntoView() 
{
      var bounds = this.ele.nativeElement.getBoundingClientRect();

      if (bounds.top < 50)
      {
          window.scrollBy(0, -50 + bounds.top );
      }
}
Simon_Weaver
  • 130,769
  • 75
  • 612
  • 659
  • 1
    I'd recommend creating a ScrollService for stuff like this that injects the element ref - then your component injects the scroll service and calls `scrollIntoView()` on it. #dry – Simon_Weaver Feb 11 '20 at 23:40