Build an Infinite Scroll Component in Angular
Building SPAs, we sometimes come across the need to display data using the technique of infinite scrolling — i.e., continuously loading data as the user scrolls down the page.
Ever since the Intersection Observer API was added to browsers, building a reusable infinite scroll component has never been easier. Let’s learn how we can create such a component using this API.
Note that we’re not going to dive into the Intersection Observer API, so if you’re not familiar with it, I recommend reading this article beforehand.
Creating the Component
The main concept is to place an observable element at the end of a list of displayed items, in order to add more data when the user reaches the bottom of that list.
We want to make as it flexible as possible, so we let our consumers pass any template they want using ng-content
. Below it, we add an anchor element which will serve as the target element that we watch.
Let’s create the Intersection Observer:
First, we create a new IntersectionObserver
which receives entries
as its argument. This function will be called whenever the observed element enters the viewport.
We can check the element’s visibility status by looking at the isIntersection
property. If isIntersecting
is true, the target element has become at least as visible as the threshold that was passed. The default threshold is 0, meaning as soon as even one pixel is visible, the callback will be run.
Next, we call the observe()
method, passing it the anchor element. This will initiate the observation of this element.
🦊 Support Scrollable Containers
The root
property indicates the element that is used as the viewport for checking the visibility of the target. When set to null
it defaults to the browser viewport.
There are times when we’ll need to have a scrollable container, and then we’d want that container to act as the root
element. Let’s support this functionality:
We add a check to see whether the current host element is a scrollable container. If it is, we set it as the root
element.
Finally, we don’t want memory leaks in our application, so we’ll disconnect the observer when the component destroyed:
It’s as simple as that.
Let’s see how we use it:
Or with a scrollable container:
Browser Support
The Intersection Observer API works in most major browsers. If you need to support old browsers such as IE, you can load a polyfill or fallback to the scroll event in runtime.
🚀 Have You Tried Akita Yet?
One of the leading state management libraries, Akita has been used in countless production environments. It’s constantly developing and improving.
Whether it’s entities arriving from the server or UI state data, Akita has custom-built stores, powerful tools, and tailor-made plugins, which help you manage the data and negate the need for massive amounts of boilerplate code. We/I highly recommend you try it out.
Follow me on Medium or Twitter to read more about Angular, Akita and JS!