Categories
Angular Answers

How to handle window scroll event in Angular and TypeScript?

Spread the love

Sometimes, we want to handle window scroll event in Angular and TypeScript.

In this article, we’ll look at how to handle window scroll event in Angular and TypeScript.

How to handle window scroll event in Angular and TypeScript?

To handle window scroll event in Angular and TypeScript, we create a custom directive.

For instance, we write

export class WindowScrollDirective {
  ngOnInit() {
    window.addEventListener("scroll", this.scroll, true); 
  }

  ngOnDestroy() {
    window.removeEventListener("scroll", this.scroll, true);
  }

  scroll = (event): void => {
    //...
  };
}

to create the WindowScrollDirective directive class.

In it, we call window.addEventListener to listen to the window’s scroll event when the directive mounts.

scroll is called when we scroll.

When we destroy the directive, we call removeEventListener to remove the scroll listener.

Conclusion

To handle window scroll event in Angular and TypeScript, we create a custom directive.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *