Wang Liang
Wang Liang

Reputation: 4434

Angular: How I can watch scroll event of all elements?

@HostListener('window:scroll', ['$event'])
public handleScroll(event: any): void {
 
}

This is working with window scroll, but, sometimes, the scroll bar is appearing on other element. so, I want to watch all events.

So, I want to like below function, but, below will make error.

@HostListener('*:scroll', ['$event'])

Upvotes: 0

Views: 675

Answers (1)

hansmaad
hansmaad

Reputation: 18905

You can add a document-level scroll event listener with useCapture parameter of true to capture the scroll events on all elements. (https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener)

Unfortunately, it's still not possible to do this with HostListener in Angular. You have to register and unregister you handler using addEventListener.

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  scroll = (e) => console.log(`scrolled: ${e.target.id}`);

  ngOnInit() {
    document.addEventListener('scroll', this.scroll, true);
  }

  ngOnDestroy() {
    document.removeEventListener('scroll', this.scroll);
  }
}

https://stackblitz.com/edit/angular-ivy-ohsjwd?file=src/app/app.component.ts

Upvotes: 1

Related Questions