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.
// write your logic here
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 !!!