How to Add Infinite Scroll on Data List in Angular 15

Using the ngx-infinite-scroll library we can implement the infinite or auto load on scroll feature in Angular application.

Ngx-infinite-scroll is a popular library for implementing infinite scrolling in Angular applications. Infinite scrolling is a technique used in web applications where additional content is loaded automaticaly as the user scrolls down the page, providing a seamless browsing experience without the need for pagination.

The ngx-infinite-scroll library provides an easy-to-use directive that can be added to any HTML element to implement infinite scrolling. The directive listens to the scrol events of the element and triggers a method when the user reaches a certain distance from the bottom of the element. This method can be used to load more content into the element, allowing the user to continue scrolling without interruption.

Some of the benefits of using ngx-infinite-scroll include:

  1. Improved user experience: Infinite scrolling provides a seamless browsing experience for users, as they can continue scrolling without having to click through to the next page.
  2. Faster page loading: By loading content on-demand as the user scrolls, you can reduce the amount of content that needs to be loaded initially, resulting in faster page load times.
  3. Reduced server load: With infinite scrolling, you only need to load the content that the user is currently viewing, reducing the load on your server and potentially saving on hosting costs.
  4. Simplified UI: Infinite scrolling eliminates the need for pagination controls, simplifying the UI and providing a cleaner user interface.

Overall, ngx-infinite-scroll is a powerful tool for improving the user experience and performance of your Angular applications.

In this example app, we will be implementing infinite scrolling using a mock remote server setup using json-server. The purpos of using json-server is to simulate a remote server that can serve JSON data via REST APIs. We will use this server to load sample data for our infinite scrolling list.

To start, we will create a simple Angular component that will contain the infinite scrolling list. We will then add the ngx-infinite-scroll directive to the container element and configure its properties and methods to achieve the desired behavior.

We will also discuss how to implement infinite scroll at page and container level so that more records gets append to respective list on scroll of their respective containers.

 

How to Add Infinite Scroll on Page and Container in Angular?

 

Step 1: Install ngx-infinite-scroll

First, you’ll need to install the ngx-infinite-scroll package using npm. Open up your terminal and navigate to your project directory, then run the following command:

npm install ngx-infinite-scroll

Step 2: Import InfiniteScrollModule and <span >HttpClientModule</span>

Next, you’ll need to import the InfiniteScrollModule and HttpClientModule to use HTTP calls into your app module. Open up your app.module.ts file and add the following import statement:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
import { InfiniteScrollModule } from 'ngx-infinite-scroll';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, HttpClientModule, InfiniteScrollModule],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

 

Step 3: Add the infinite scroll directive to your component

Now, you can use the infinite scroll directive in your component. Open up the component where you want to implement infinite scrolling and add the following code to the template:

<div class="scrollable-content" 
    infiniteScroll 
    [infiniteScrollDistance]="2"
    [infiniteScrollThrottle]="500" 
    (scrolled)="onScroll()">
    <div *ngFor="let item of items">{{ item.name }}</div>
</div>

Let’s break down what each of these properties does:

  • infiniteScroll: This is the directive that enables infinite scrolling.
  • infiniteScrollDistance: This property sets how far the user must scroll down from the bottom of the container before the scrolled event is emitted. In this example, the event will be emitted when the user is within 2 screen heights of the bottom of the container.
  • infiniteScrollThrottle: This property sets the number of milliseconds to wait before emitting the scrolled event again. In this example, the event will be emitted at most once every 500 milliseconds.
  • (scrolled): This is the event that is emitted when the user scrolls to the bottom of the container. In this example, it will call the onScroll() method.

 

Step 4: Implement the onScroll() method

Now that we have our template set up, let’s implement the onScroll() method in our component. Add the following code to your component class:

import { Component } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  items: any[] = [];
  page = 1;
  pageSize = 5;
  hasMoreData = true;

  constructor(private dataService: DataService) {}

  ngOnInit() {
    this.loadMoreData();
  }

  onScroll() {
    console.log('onScroll');
    if (this.hasMoreData) {
      this.page++;
      this.loadMoreData();
    }
  }

  loadMoreData() {
    this.dataService.getItems(this.page, this.pageSize).subscribe((items) => {
      if (items.length === 0) {
        this.hasMoreData = false;
      } else {
        this.items = [...this.items, ...items];
      }
    });
  }
}

We have added a page property and a hasMoreData property to keep track of the current page number and whether there’s more data to load. In the onScroll() method, we increment the page number and call the loadMoreData() method to fetch more data.

The loadMoreData() method calls the getItems() method of our data service to fetch more items. If there are no more items to load, we set hasMoreData to false. Otherwise, we append the new items to the existing items array using the spread operator (...).

 

Step 4: Create a service to fetch data

Now, create a new service called data.service.ts that will fetch the data from json-server. Add the following code to the service:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root',
})
export class DataService {
  private apiUrl = 'http://localhost:3000/items';

  constructor(private http: HttpClient) {}

  getItems(page: number, pageSize: number) {
    const skip = (page - 1) * pageSize;
    const take = pageSize;

    return this.http.get<any[]>(`${this.apiUrl}?_start=${skip}&_limit=${take}`);
  }
}

Step 5: Install json-server and create a JSON file

Next, we will creat a mock server using json-server . Open up your terminal and run the following command:

npm install -g json-server

Next, create a new file called data.json and add some data to it. For example:

{
  "items": [
    { "id": 1, "name": "Item 1" },
    { "id": 2, "name": "Item 2" },
    { "id": 3, "name": "Item 3" },
    { "id": 4, "name": "Item 4" },
    { "id": 5, "name": "Item 5" },
    { "id": 6, "name": "Item 6" },
    { "id": 7, "name": "Item 7" },
    { "id": 8, "name": "Item 8" },
    { "id": 9, "name": "Item 9" },
    { "id": 10, "name": "Item 10" }
  ]
}

 

Step 6: Start json-server

Once you have your data file ready, start json-server by running the following command:

json-server --watch data.json

This will start a web server at http://localhost:3000 that serves your JSON data.

 

How to Load Infinite Items in Container instead of Page Scroll?

By default the onScroll() method is getting called when the page scrolls instead of the div element, to make it trigger on specific container’s scoll, add the scrollWindow property to the infiniteScroll directive and set it to false. This will make sure that the onScroll() method is only triggered when the user scrolls within the div element, and not the entire page.

Updated template of the code with the scrollWindow property added:

<div class="scrollable-content" style="height: 100px;overflow: auto;" 
    infiniteScroll 
    [infiniteScrollDistance]="2"
    [infiniteScrollThrottle]="500"
    [scrollWindow]="false" 
    (scrolled)="onScroll()">
    <div *ngFor="let item of items">{{ item.name }}</div>
</div>

By setting scrollWindow to false, the infiniteScroll directive will only listen to the scroll events of the div element and not the entire window.

Conclusion

The ngx-infinite-scroll is a powerful tool for implementing infinite scrolling in Angular applications. It allows you to load more data as the user scrolls down, providing a seamless and uninterrupted experience. By using a mock remote server setup with json-server, we were able to demonstrate how to use various properties and methods of ngx-infinite-scroll.

We also showed how to load more records on both page scroll and div container scroll, depending on your specific use case. With some well-designed CSS, you can create a beautiful and functional infinite scroll container that is both easy to use and visually appealing.

Leave a Comment

Your email address will not be published. Required fields are marked *