Window scroll event using @HostListener not working Window scroll event using @HostListener not working typescript typescript

Window scroll event using @HostListener not working


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');}


Your layout must be the source of the issue. The scroll event works only when the the component template element can actually scroll.

Make sure the div has overflow property set to scroll. Also, change the div dimensions so the scroll could trigger.

In order to make it work, I would suggest to make it to the directive and set to a div that has 100vh in height and 100vw in width.

import { Directive, ElementRef, HostListener } from '@angular/core';@Directive({ selector: '[trackScroll]' })export class TrackScrollDirective {    constructor(private el: ElementRef) {    }    @HostListener('document:scroll', [])    onScroll(): void {         console.log('I am scrolled');    }} 

See this stackblitz that I made.


This should give you scroll events:

@HostListener('scroll', ['$event'])onScroll(event) {  ...}

or

<div (scroll)="onScroll($event)"