Scroll Event is not firing in Angular-6

9.4k Views Asked by At

I know this question is asked before, but none of the solutions worked for me.

I am working on the Angular-6 project. I am trying to get Window-Scroll event in one of the components named SectionComponent.

Styles of html and body tag:

html, body {
    overflow: auto;
    position: relative;
    margin: 0;
    height: 100%;
}

Below is the hierarchy of components which explains how components are managed.

My AppComponent:

HTML:

<div id="wrapper">
    <router-outlet></router-outlet>  
</div>

CSS:

#wrapper {
    width: 100vw;
    height: 100vh;
    position: relative;
    overflow: auto;
}

app.component.ts:

  @HostListener('window:scroll', [])
  onWindowScroll() {
    console.log('scroll');
  }

AppComponent loads component named HomeComponent in the router-outlet tag. This HomeComponent loads SectionComponent by using is selector.

My HomeComponent:

HTML:

<div class="home-wrapper">
  <div> 
    <!-- Some content more that window height -->
  </div>
  <app-section></app-section>
</div>

CSS:

.home-wrapper {
    position: relative;
    overflow-y: auto;
    height: 100%;
}

home.component.ts:

  @HostListener('window:scroll', [])
  onWindowScroll() {
    console.log('scroll');
  }

My SectionComponent

HTML:

<div class="section-wrapper">
  <!-- Some content more than window height -->
</div>

CSS:

.section-wrapper {
  position: relative;
  height: 2241px;
}

section.component.ts:

  @HostListener('window:scroll', [])
  onWindowScroll() {
    console.log('scroll');
  }

I only want to use Window-Scroll in SectionComponent. But none of the components are firing the event. What am I doing wrong?

2

There are 2 best solutions below

1
On
import { ScrollDispatcher } from '@angular/cdk/scrolling';

  constructor(private scrollDispatcher: ScrollDispatcher) {    
    this.scrollDispatcher.scrolled().subscribe(x => console.log('I am scrolling'));
  }

in tempalte:

<div cdkScrollable>
  <div *ngFor="let one of manyToScrollThru">
    {{one}}
  </div>
</div>
0
On

In Your SectionComponent after the class declaration just use

@HostListener('window:scroll', ['$event']) onScrollEvent($event){

var element =  document.getElementsByClassName('section-wrapper')[0];
var rect =   element.getBoundingClientRect();
 // the above code will return the CSS border-boxe associated with the element.
// so on scroll you will have readonly left, top, right, bottom, x, y, width, and height properties .
//on behalf of these properties you can manipulate the DOM section-wrapper div.

}