Window scroll event using @HostListener not working

tolceza picture tolceza · Aug 29, 2017 · Viewed 18.9k times · Source

I have problem making sticky header when scrolling down, in an Angular 4 application. Scroll event can't be detected.

Header is placed in the layout component, and the content I want to be scrolling is placed in routes component. May that be the problem?

This is the code I implemented.

In layout.component.ts

import { Component, OnInit, HostListener, Inject } from '@angular/core';

import { DOCUMENT } from "@angular/platform-browser";

@Component({

  selector: 'app-layout',

  templateUrl: './layout.component.html',

  styleUrls: ['./layout.component.css']
})

export class LayoutComponent implements OnInit {

  public navIsFixed: boolean = false;

  constructor(public router: Router, @Inject(DOCUMENT) private document: any) { }

  @HostListener('window:scroll', [ ])

    onWindowScroll(){
      const number = window.pageYOffset || 
      document.documentElement.scrollTop || 
      document.body.scrollTop || 0;
      if (number > 50) {
        this.navIsFixed = true;
      } else if (this.navIsFixed && number < 10) {
      this.navIsFixed = false;
      }
    }
}

In layout.component.html

<div [class.fixed]="navIsFixed" class="header">

Answer

Zahema picture Zahema · Jun 10, 2018

I just had the same problem, all what I had to do was to make sure that the component element is actually what is scrolling & that it has a overflow property with values scroll or auto.

Otherwise just this worked:

@HostListener('scroll')
  public asd(): void {
  console.log('scrolling');
}