Working with Angular<ng> is fun but when displaying hundreds of feed items ala facebook the older mobile devices can't handle it. Good thing there is a virtual scroller from the material CDK but it does not fit my needs. The experimental version is still buggy and jumpy at times.
Now I'll show you how to do virtual scrolling without using any third party library in Angular. It's a very simple solution and only involves a bit of coding.
Keep in mind the page items you want to display. For this exercise we need to display 20 feeds per page.
This line will determine if we loaded enough feeds so we can limit the number of feeds per next load and increment the <beginFeeds> variable accordingly.
if(this.pageLoad > this.beginFeeds + 40){
this.beginFeeds += 20;
}
If the <pageLoad> is more than 40 items than the <beginFeeds>, it should increment 20 items for the <beginFeeds> variable.
We set the scroll event listener so when our button element's top is above the viewport it will call the feed loader.
ngOnInit(){
window.addEventListener('scroll', eScroll, false);
}
This line will set the feeds hidden variable to true so we can check it on an *ngIf compare and hide our div
for(i=0; i < this.feeds.length; i++){
this.feeds[i].hidden = true;
if(i < this.beginFeeds){
this.feeds[i].hidden = false;
}
}
This line increments the <pageLoad> variable for the next data fetch.
If we keep loading data it will only show non-hidden items and free some precious resources.
What if the user scrolls to the beginning? Don't worry my friend. We got it handled.
loadLess = () => {
if(this.beginFeeds - 20 < 0 ) return;
let start = this.beginFeeds - 20;
let end = this.beginFeeds + 40;
for(var i=0; i < this.feeds.length; i++){
this.feeds[i].hidden = true; //hide all feeds
}
for(i=start; i < end; i++){
this.feeds[i].hidden = false; //unhide feeds in range
}
}
This line will check if our <beginFeeds> variable is greater than zero and get out if it is.
if(this.beginFeeds - 20 < 0 ) return;
Set our beginfeeds to decrement 20 items.
let start = this.beginFeeds - 20;
Set the range to <beginFeeds> plus 40 items.
let end = this.beginFeeds + 40;
Loop through the feeds and set feed items inside the range its hidden variable to false so it will show on the page. Then we'll employ Angular's last item check after its done the *ngFor loop and call our special function to seamlessly scroll back to the feed we are in.
for(var i=0; i < this.feeds.length; i++){
this.feeds[i].hidden = true; //hide all feeds
}
for(i=start; i < end; i++){
this.feeds[i].hidden = false; //unhide feeds in range
}
That's it! that will get you a fairly decent vertical scroll pagination on scroll.
Here's the StackBlitz
Buy me a cup of coffee :)