Ionic 5/4 Adding Infinite Scroll to Auto Load More Items Example Application

In this post, we will discuss How to implement item loader component which auto-loads new items from the server or local data-object and appends to the list with a smooth animation when user scrolls to bottom.

Desktop-based applications show a large set of data in tabular form with pagination which allows a user to navigate or jump to a specific row set by clicking on page numbers. But the mobile application is different in terms of limited screen area and memory. We can’t show tables to display data due to limited screen space. Also, we can’t load all data at once to prevent performance issues.

In such a case, we can display data in the form of a list which can be easily scrolled by the user in verticle direction to display more items. Ionic Framework provides us Infinite-Scroll component using which we can load only a limited number of items like 15-25 to display, after a user scroll downs to view more, the infinite-scroll component load more items and appends to the list.

The Infinite scroll is implemented by adding the <ion-infinite-scroll> directive component. To demonstrate a working example, we’ll create a list of employees which will be loaded from a mock JSON API server using the infinite-scroll component.

Let’s get started!

#Update @ionic/cli

We’ll be going to create an Ionic application with @ionic/cli version 6.13.4

You can upgrade to the latest version by running the following npm command

$ npm install -g @ionic/cli</pre>
 
<h3>#Create an Ionic Application</h3>
For our example, we'll create a new Ionic application with a <code>blank template using Angular framework.

Run following ionic command in the terminal window
$ ionic new ionic-infinite-scroll-app blank --type=angular</pre>
 
<h3>#Adding HttpClientModule</h3>
To make server calls using Http methods, we need to import the <code>HttpClientModule in the App's module.

Open the app.module.ts file then import the HttpClientModule then update the imports array as shown below:
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule,
    IonicModule.forRoot(),
    AppRoutingModule,
    HttpClientModule
  ],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

 

#Creating a Fake/ Mock Server

For testing purposes, we can create a mock or fake server using the json-server to create a dummy database using a JSON file and put random employees data using faker package. We have explained how to set up, create and run a mock server in Ionic and Angular applications here.

We recommend you to check that post if you don't have any server to test this feature using HTTP server APIs. It will hardly take 2 minutes to get a running test server.

After completing steps explained here, you will have a local server up and running at this location http://localhost:3000/employees

Each employee object will have the following properties:

{
 "id":1,
 "name":"Lilla Nitzsche",
 "jobtype":"Human Intranet Liaison",
 "email":"[email protected]",
 "address":"11360 Bahringer Squares",
 "imageUrl":"https://s3.amazonaws.com/uifaces/faces/twitter/aleclarsoniv/128.jpg"
}</pre>
 

 
<h3>#Setup Service for HTTP calls</h3>
For making server calls, we highly recommend creating a separate service file to have methods to make any server calls using HttpClient module.

Here we will create a <code>HttpConfigService to add a getListItems() making a get call.

Run the following command to generate a new service file under services folder
$ ionic generate service services/http-config</pre>
This will create a service at <strong>~src/app/services/http-config.service.ts </strong>Update the file content as shown below:
<pre class="wp-block-prismatic-blocks"><code class="language-javascript">// http-config.services.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class HttpConfigService {

  // API path 
  base_path = 'http://localhost:3000/employees';

  constructor(
    private http: HttpClient
  ) { }

  getListItems(params) {
    console.log(this.base_path + params);
    return this.http.get(this.base_path + params);
  }

}
</pre>
 
<h3>#Adding Infinite-Scroll</h3>
In the Home Page, we'll show a list of Employee in a <code><ion-list> component with each employee in an <ion-item>
  <ion-list>

    <ion-item *ngFor="let employee of itemListData">
      <ion-avatar slot="start">
        <img [src]="employee.imageUrl">
      </ion-avatar>
      <ion-label>
        <ion-text>
          <h2>{{employee.name}}</h2>
          <p>{{employee.jobtype}}</p>
        </ion-text>
        <ion-text color="medium">
          <p>{{employee.email}}, {{employee.address}}</p>
        </ion-text>
      </ion-label>
    </ion-item>

  </ion-list></pre>
Now, below this <code><ion-list> we will add the <ion-infinite-scroll> with a <ion-infinite-scroll-content> component in it.


<ion-header [translucent]="true">
  <ion-toolbar>
    <ion-title>
      Ionic Infinite List
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true" class="ion-padding">


  <ion-list>

    <ion-item *ngFor="let employee of itemListData">
      <ion-avatar slot="start">
        <img [src]="employee.imageUrl">
      </ion-avatar>
      <ion-label>
        <ion-text>
          <h2>{{employee.name}}</h2>
          <p>{{employee.jobtype}}</p>
        </ion-text>
        <ion-text color="medium">
          <p>{{employee.email}}, {{employee.address}}</p>
        </ion-text>
      </ion-label>
    </ion-item>

  </ion-list>

  <ion-infinite-scroll (ionInfinite)="doInfinite($event)">
    <ion-infinite-scroll-content loadingSpinner="bubbles" loadingText="Loading more data...">
    </ion-infinite-scroll-content>
  </ion-infinite-scroll>


</ion-content>

The (ionInfinite) event trigger will take care of loading more items when a user scrolls to the bottom of the page.

 

# Update Home Component Class

Now we have our Home template ready, let's update the class. First, import the HttpConfigService then add in the constructor function.

Also, define some variables for the URL, current page and number of items to load per hit.

  url: string;
itemListData = [];
page_number = 1;
page_limit = 8;</pre>
In the <code>ngOnInit()
component hook we will call the getEmployees() method to make the server call and fetch records

The doInfinite() method will be added, which will be triggered by the infinite-scroll component's (ionInfinite) event.

Finally, out complete home.page.ts file will look like this:

//home.page.ts
import { Component } from '@angular/core';
import { HttpConfigService } from '../services/http-config.service';

@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {

url: string;
itemListData = [];
page_number = 1;
page_limit = 8;

constructor(
private httpConfigService: HttpConfigService
) { }

ngOnInit() {
this.getEmployees(false, "");
}

getEmployees(isFirstLoad, event) {

this.url = '?_page=' + this.page_number + '&_limit=' + this.page_limit;

this.httpConfigService.getListItems(this.url)
.subscribe((data: any) => {

for (let i = 0; i < data.length; i++) {
this.itemListData.push(data[i]);
}

if (isFirstLoad)
event.target.complete();

this.page_number++;
}, error => {
console.log(error);
})
}

doInfinite(event) {
this.getEmployees(true, event);
}

}
</pre>
The<code> event.target.complete()

will hide the loader showing on the bottom indicates the loading is completed. After the request is successfully completed, we are incrementing the page_number by 1 so that the next call will fetch the new set of items.

That's it now you can run your application by hitting $ ionic serve --open.

Make sure to run your local server as well by running $ json-server --watch ./server/data.json in the terminal.

Conclusion: In this post, we discussed how to implement the infinite-scroll component to load items on a scroll from the server. You can check more details in the official documentation here.

Thanks for reading!

 

1 thought on “Ionic 5/4 Adding Infinite Scroll to Auto Load More Items Example Application”

  1. Hi. Thanks for this tutorial about ionic, it is very clear. Only needs one modification in the function getEmployees
    this.page_number++
    must be changed to:
    this.page_number = this.page_number + this.page_limit

    Great job!

Leave a Comment

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