Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular check when an element is in view

Tags:

angular

In angular, how do I detect if a certain element is in view?

For example, I have the following:

<div class="test">Test</div>

Is there a way to detect when this div is in view?

Thanks.

like image 610
Steve Kim Avatar asked Mar 11 '18 01:03

Steve Kim


1 Answers

Based off this answer, adapted to Angular:

Template:

<div #testDiv class="test">Test</div>

Component:

  @ViewChild('testDiv', {static: false}) private testDiv: ElementRef<HTMLDivElement>;
  isTestDivScrolledIntoView: boolean;

  @HostListener('window:scroll', ['$event'])
  isScrolledIntoView(){
    if (this.testDiv){
      const rect = this.testDiv.nativeElement.getBoundingClientRect();
      const topShown = rect.top >= 0;
      const bottomShown = rect.bottom <= window.innerHeight;
      this.isTestDivScrolledIntoView = topShown && bottomShown;
    }
  }

Example with scroll event binding

Another nice feature is to determine how much of that <div> is to be considered as "within view". Here's a reference to such implementation.

like image 129
noamyg Avatar answered Sep 19 '22 16:09

noamyg