DEV Community

loading...

Angular infinite scrolling using RxJS and NgRx

Anirban Mukherjee
Love anything angular and angular-y
Originally published at theangularpath.anirbanblogs.com Updated on ・2 min read

GitHub logo anirbmuk / angular-scroll-demo

Angular 12 application to demonstrate infinite scrolling with RxJS and NgRx

I have seen multiple blog posts on this topic which make use of one method or the other. I just thought of putting everything together under one hood - RxJS, NgRx, Angular Material and in the end, pure document property access. This is what is leads to:

Preview

Let's quickly talk about the setup here - I am using an Angular CLI 12.1.0 project. I have NgRx state management set up, with a root state and a feature state. Of course, NgRx is in no way related to the purpose of this application, but I just thought it would not hurt to implement it. We have to admit, as your application grows in size, NgRx does give you some peace of mind :-)

The UI is built using angular material. I have used the mat-list and and the mat-spinner components. I have some hard-coded dummy data, which I have converted into an observable stream, with a delay of 1500 ms, which gives some feeling of having fetched data from a REST service.

The key logic is to calculate when the user has scrolled down to the edge of the page. I chose a simple formula derived from the document object. Of course there are other fancy approaches like using an IntersectionObserver, but that's something I felt was too much for me!

data.service.ts
The above formula works great on a desktop, as well as a mobile - but feel free to drop me a note if it doesn't.

I set up the scroll action using RxJS fromEvent.
data.service.ts

Once the scroll event is set up, whenever the above formula is satisfied, the next set of data is called for. For my sample use case, I have used a limit and skip value, which I have used to slice off a chunk from my dummy data set. Every time a new set is emitted by my data observable, I have made use of a reducer function to append it to my previous list of data.

feature.reducer.ts

This is where I store the next limit and skip values for the next data load, and also make a simple calculation of whether my data load is complete, and set it on my state. Once this flag becomes true, subsequent scroll actions do not trigger any more data fetch.

data.service.ts

Cheers :-)

Discussion (0)