How To Handle Scroll Event In Angular?

While working with one of the angular projects, I got the requirement as below which need to handle scroll event in angular.

There was the small view (let’s say partial view), and data from the API need to be loaded at that view using angular “*ngFor” for looping through the collection of data. When the data on the database increases, it is the time-consuming practice to load all the data when the application starts.

So, I decided to load them in the small chunk every time when the user scrolls the view. Something like loading the chat history in any of the social media application.

For that first of all I need to handle scroll event in angular.

Development Environment: Angular V5.2.5

Below is the code for handling the scroll event on HTML div using angular.

Binding an event on the markup using angular is simple. Here (scroll) is the event name and LoadMoreData is the function that you will implement on your component.

Please make sure the div is scrollable. Otherwise, the scroll event will not be fired.

Below is the code that implements the function registered with the scroll event.

Here the function LoadMoreData() is decorated with the decorator @HostListener. The @HostListener lets you listen for events on the host element or component.

The logic after the scroll event is based on your requirement.

Hope this helps you.

Have a great day !!!

About dipneupane

Dip is a passionate Software Developer based in Kathmandu, Nepal. He chew code and smash keyboard for living. Apart from that, he writes about almost everything on buzzedcode.com.

View all posts by dipneupane →

One Comment on “How To Handle Scroll Event In Angular?”

Leave a Reply

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