Infinite Scrolling in Angular
You’re definitely familiar with endless scroll if you’ve ever had to navigate through lengthy lists in a web application. A frequent solution to the issue of providing a lengthy list to your consumers at the right time is infinite scrolling. In this article, we’ll use the ngx-infinite-scroll package to add an infinite scroll to Angular.
This tutorial will cover how to quickly and easily construct the endless scrollable component using the powerful npx-infinite-scroll
package. Additionally, we will review all crucial attributes and event setups to increase flexibility for your app.
Introduction To Infinite Scroll
In some cases, we have a lot of data to display on the user displays, therefore infinite signifies that there is no end to it. However, we are unable to load all the data at once and present it on the screen. If this is the case, it will take a very long time to load and, even after loading, will be difficult for browsers with low rendering power to handle.
We can load data from the server to the user’s screen in chunks by employing the endless method. In this method, we may load more data and feed it to the scrollable container as the user consumes prior data and scrolls down. Because we don’t fetch all the data at once that isn’t necessary, applications with infinite features are more effective, user-friendly, and data-saving.
What’s the importance of this technique?
- You may expand the amount of content that users interact with by using infinite scroll (also known as page depth).
- Sites become enticing as a result. People become engrossed in the information and spend what seems like an eternity on the website.
- less clicks, greater content exposure, and responsiveness to varied devices all contribute to an improved user experience.
Setting up our Angular Application
Make sure you have Angular CLI installed on your machine before executing the command below so that you can create the Angular application. We’ll also add Angular Material to our page.
ng new infinite-scroll --routing=false --style=scss --skip-tests
ng add @angular/material
After that we’ll install our ngx-Infinite-scroll
package with the following command.
npm i ngx-infinite-scroll
After the package has been installed, we must set up the App Module to import the necessary components. so that the application as a whole can use the Infinite Scroll component directive. InfiniteScrollModule
may now be imported in app.module.ts and added to our imports. We’ll need MatCardModule
and HttpClientModule
eventually, so let’s do the same with them.
...
import { HttpClientModule } from '@angular/common/http';
import { MatCardModule } from '@angular/material/card';
import { InfiniteScrollModule } from ‘ngx-infinite-scroll’;
...
imports: [..., HttpClientModule, MatCardModule, InfiniteScrollModule],
...
Adding Infinite Scroll Component
The Infinite Scroll component will now be added to the app.component.html Component. The infinite-scroll directive, along with a few other properties and event handlers, can be used to build an infinitely scrollable container.
<div
infinite-scroll
[infiniteScrollDistance]="distance"
[infiniteScrollThrottle]="throttle"
(scrolled)="onScroll()"
>
...
</div>
Although the div
container in the example above with the infinite properties, the infinite-scroll directive feature is crucial for making the element truly infinitely scrollable. Let’s say:
- When the user scrolls 90% of the way down the page,
onScroll()
will be called if[infiniteScrollDistance]
is set to 1. If two, then 80%, and so forth. - If
[infiniteScrollThrottle]
is set to 500,onScroll()
won’t run until the user has not scrolled for 500 milliseconds. - According to the aforementioned properties, the event
(scrolled)
is the one that occurs when a user scrolls down.
Open Source Session Replay
OpenReplay is an open-source, session replay suite that lets you see what users do on your web app, helping you troubleshoot issues faster. OpenReplay is self-hosted for full control over your data.
Start enjoying your debugging experience - start using OpenReplay for free.
Integrate a Fake API for our DB
We want something like this:
In such case we’ll integrate a Fake API to out project app which will be use to get our dummy data. [object JSON] Placeholder is a free fake API for testing and prototyping. Powered by JSON Server + Low DB. Tested with XV.
Let’s create an interface for a comment.
ng g i comment --type=model
export interface Comment {
id: number;
name: string;
email: string;
body: string;
}
Let’s now build a service to retrieve the commentaries.
ng g s comment
We wish to leverage the List Comments endpoint of the API in our service. Visit the endpoint at https://jsonplaceholder.typicode.com/comments see for yourself. If you do, you’d notice that it’s already been formatted by JSON Formatter.
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Comment } from './comment.model'
@Injectable({
providedIn: 'root'
})
export class CommentService {
constructor(private http: HttpClient) {}
getCommentaries(page: number): Observable<Comment[]> {
return this.http.get(
`https://jsonplaceholder.typicode.com/comments?page=${page}&per_page=10`
) as Observable<Comment[]>;
}
}
Now, when the page loads, our component loads the first set of comments. The following set of comments are then retrieved since every time the user scrolls, the page advances by one.
import { Component, OnInit } from '@angular/core';
import { Comment } from './comment.model';
import { CommentService } from './comment.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
throttle = 0;
distance = 2;
page = 1;
commentaries: Comment[] | any[] = [];
constructor(private commentService: CommentService) {}
ngOnInit(): void {
this.commentService
.getCommentaries(this.page)
.subscribe((commentaries: Comment[]) => {
this.commentaries = commentaries;
});
}
onScroll(): void {
this.commentService
.getCommentaries(++this.page)
.subscribe((commentaries: Comment[]) => {
this.commentaries.push(...commentaries);
});
}
}
Now, let’s go back to our Infinite Scroll component and update our component with a list of Angular Material Card that will caryy each commentary data.
<div
infinite-scroll
[infiniteScrollDistance]="distance"
[infiniteScrollThrottle]="throttle"
(scrolled)="onScroll()"
>
<mat-card *ngFor="let comment of commentaries">
<mat-card-title>
<h1>
<a [href]="comment.website_url">{{ comment.name }}</a>
</h1>
</mat-card-title>
<mat-card-subtitle>
<h2>{{ comment.email }}</h2>
</mat-card-subtitle>
<mat-card-content>
<h3>Type: {{ comment.body }}</h3>
</mat-card-content>
</mat-card>
</div>
Let’s run our project with the following command:
ng serve
When I scroll 80% down the page, you can see how the scrolling bar returns to its initial position, indicating that more data has been loaded
Conclusion
Many prestigious brands employ the ngx-infinite-scroll package, which is very well-liked. This package has a large variety of customizable attributes and methods, making configuration quite versatile. We spoke about how to rapidly add the infinite scrollbar feature to an Angular application and how it has benefited the development community. Also have a look at the source code on Github for references.
Resources
A TIP FROM THE EDITOR: For implementations of infinite scrolling with other frameworks, read our Infinite Scrolling in Vue using the Vue Intersection Observer API and Infinite scrolling with React Query articles.