
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 APIwas 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.
@Component({ | |
selector: 'infinite-scroll', | |
template: `<ng-content></ng-content><div #anchor></div>` | |
}) | |
export class InfiniteScrollComponent implements OnInit, OnDestroy { | |
... | |
ngOnInit() { | |
const options = { | |
root: null, | |
...this.options | |
}; | |
this.observer = new IntersectionObserver(([entry]) => { | |
entry.isIntersecting && this.scrolled.emit(); | |
}, options); | |
this.observer.observe(this.anchor.nativeElement); | |
} | |
} |
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:
ngOnDestroy() { | |
this.observer.disconnect(); | |
} |
Comments
Post a Comment