How to implement infinite scroll in Angular
Infinite scrolling is a UX pattern that loads additional content as the user scrolls down a page. Unlike traditional pagination, where content is divided into separate pages, infinite scroll keeps adding content to the existing page until the user has consumed all available data. This technique is efficient for enhancing the user experience, especially on mobile devices, as it reduces the need for repetitive clicks and reloads
Setting up the Angular project
To get started, you need to create a new Angular project or use an existing one. If you’re starting fresh, run the following command to generate a new project:
ng new infinite-scroll-demo
After the project is created, navigate into the project directory:
cd infinite-scroll-demo
Now, install the ng-inf-scroll library, which will help us implement infinite scrolling with ease:
npm install ng-inf-scroll
Adding Infinite Scroll to Your Component
Let’s create a simple component that implements infinite scrolling. We’ll start by generating a new component called post-list:
In this component, we will display a list of posts that get appended to the list as we scroll down.
Step 1: Add HTML Template
First, update the post-list.component.html file to include a container that will hold our data:
<div class="post-container" infScroll (scrolled)="scrolled()">
@for (post of posts; track $index) {
<div class="post-item">
<h3>{{ post.title }}</h3>
<p>{{ post.body }}</p>
</div>
}
</div>Step 2: Add Component Logic
Now, let’s add some logic to post-list.component.ts to handle fetching and displaying data. We'll simulate fetching posts by using a mock data array:
import { Component, OnInit } from '@angular/core';
import { InfScroll } from 'ng-inf-scroll';
interface Post {
title: string;
body: string;
}
@Component({
selector: 'app-post-list',
templateUrl: './post-list.component.html',
styleUrls: ['./post-list.component.scss'],
standalone: true,
imports: [InfScroll],
})
export class PostListComponent implements OnInit {
posts: Post[] = [];
private currentPage = 1;
constructor() {}
ngOnInit(): void {
this.loadPosts();
}
scrolled(): void {
this.currentPage++;
this.loadPosts();
}
private loadPosts(): void {
// Mock data fetching
console.log('Loading more');
for (let i = 0; i < 10; i++) {
this.posts.push({
title: `Post Title ${i + (this.currentPage - 1) * 10}`,
body: `This is the body of post ${i + (this.currentPage - 1) * 10}`,
});
}
}
}In this example:
- We maintain an array of
poststo keep track of the posts that need to be displayed. - The
scrolled()method increments the page number and fetches more posts. - The
loadPosts()method simulates loading data by appending new posts to thepostsarray.
Styling the Component
Add some basic styling to make the posts look better. Update the post-list.component.css file:
.post-container {
width: 80%;
margin: 0 auto;
max-width: 600px;
height: 600px;
overflow-y: auto;
}
.post-item {
border: 1px solid #ddd;
padding: 16px;
margin-bottom: 16px;
border-radius: 8px;
background-color: #fff;
}Testing the Infinite Scroll
Now that everything is set up, you can run the Angular application:
ng serve
Navigate to http://localhost:4200/, and you should see the posts loading as you scroll down.
