Infinite scroll is the popular replacement for pagination. It has the same function as pagination for limiting the displayed list of data on the view. So, we will show you the real example infinite scroll on the Ionic 3 mobile app. `The Real Example` means we'll use data from the REST API, not from the local array variable. For this tutorial, we use the latest Ionic 3 and Angular 4 version. Before go deeply with the example, you have to prepare the tools, frameworks, modules, and dependencies.
Jumps to the steps:
The following tools, framework, and dependencies are required for this tutorial:
- Node.js (use stable and recommended version)
- Ionic 3
- REST API End point
- Terminal or Node Command Line
- Text Editor or IDE
After installing Node.js and able to run Node command line, run this command in the terminal or Node command line to install or update latest Ionic and Cordova.
sudo npm install -g ionic cordova
Create New Ionic 3 Angular 4 App
As usual, in our tutorial start by creating new Ionic 3 Angular 4 app from scratch. In the terminal or Node command line run this command.
ionic start ionic-infinite-scroll blank
Next, go to your newly created app folder.
cd ionic-infinite-scroll
Now, test the newly created app to make sure everything working properly by run this command.
ionic serve --lab
You should see this page open automatically on the default browser.
Implementing Infinite Scroll or Load More
Now, its a time for implementing infinite scroll or load more feature to the Ionic 3 and Angular 4 app. First, create a provider or service for getting data from the REST API. Type this command on the terminal or Node command line to create it.
ionic g provider rest-api
Open and edit `src/providers/rest-api/rest-api.ts` file then make the imports of Injectable, Http, Response, Observable, RxJS Operator catch, and map.
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
Declare this variable before the constructor.
private apiUrl = 'https://reqres.in/api/';
We are using free REST API service for testing from the Resreq. Now, add the function after constructor to getting data from REST API then extract and map response as Observable.
getUsers(page): Observable<string[]> {
return this.http.get(this.apiUrl+"users?page="+page)
.map(this.extractData)
.catch(this.handleError);
}
Add function for extract data that previously get from the Http response.
private extractData(res: Response) {
let body = res.json();
return body || { };
}
Add function to handle the error and returning as Observable.
private handleError (error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
Don't forget to add `HttpModule` to `src/app/app.module.ts`. Open and edit that file then add this import of HttpModule.
import { HttpModule } from '@angular/http';
Add `HttpModule` to `@NgModule` imports, so it will look like this.
imports: [
BrowserModule,
IonicModule.forRoot(MyApp),
HttpModule
],
Now, open and edit current `src/pages/home/home.ts` then add this import of RestApiProvider.
import { RestApiProvider } from '../../providers/rest-api/rest-api';
Declare these variables before the constructor.
data: any;
users: string[];
errorMessage: string;
page = 1;
perPage = 0;
totalData = 0;
totalPage = 0;
Inject `RestApi` provider inside constructor.
constructor(public navCtrl: NavController, public restApi: RestApiProvider) {}
Create a function for getting Users data.
getUsers() {
this.restApi.getUsers(this.page)
.subscribe(
res => {
this.data = res;
this.users = this.data.data;
this.perPage = this.data.per_page;
this.totalData = this.data.total;
this.totalPage = this.data.total_pages;
},
error => this.errorMessage = <any>error);
}
Call that function inside constructor body.
constructor(public navCtrl: NavController, public restApi: RestApiProvider) {
this.getUsers();
}
Create a function for implementing an infinite scroll.
doInfinite(infiniteScroll) {
this.page = this.page+1;
setTimeout(() => {
this.restApi.getUsers(this.page)
.subscribe(
res => {
this.data = res;
this.perPage = this.data.per_page;
this.totalData = this.data.total;
this.totalPage = this.data.total_pages;
for(let i=0; i<this.data.data.length; i++) {
this.users.push(this.data.data[i]);
}
},
error => this.errorMessage = <any>error);
console.log('Async operation has ended');
infiniteScroll.complete();
}, 1000);
}
Next, we will implement infinite scroll on the view. Open and edit `src/pages/home/home.html` then replace all `<ion-content>` with these tags of <ion-content>, <ion-card>, and <ion-list> that contain list from the users array.
<ion-content padding>
<ion-card>
<ion-card-header>
Infinity Scroll Example
</ion-card-header>
<ion-card-content>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
</ion-card-content>
</ion-card>
<ion-list>
<ion-item *ngFor="let user of users">
<ion-avatar item-start>
<img src="{{user.avatar}}">
</ion-avatar>
<h2>{{user.first_name}} {{user.last_name}}</h2>
</ion-item>
</ion-list>
<ion-infinite-scroll (ionInfinite)="doInfinite($event)" *ngIf="page < totalPage">
<ion-infinite-scroll-content loadingSpinner="bubbles" loadingText="Loading more data..."></ion-infinite-scroll-content>
</ion-infinite-scroll>
</ion-content>
We put static paragraph because initial data and infinite scroll data show only 3 rows per page, so we need to cover the rest of the page with the static paragraph.
Now, you can test run the app in the browser and see infinite scroll or load more functionality working.
That is for now, you can find the full source code on our GitHub.
We know that building beautifully designed Ionic apps from scratch can be frustrating and very time-consuming. Check Ionic 4 - Full Starter App and save development and design time. Android, iOS, and PWA, 100+ Screens and Components, the most complete and advance Ionic Template.
That just the basic. If you need more deep learning about Ionic, Angular, and Typescript, you can take the following cheap course:
- IONIC 4 Design Hybrid Mobile Applications IOS & Android
- Wordpress Rest API and Ionic 4 (Angular) App With Auth
- Mobile App from Development to Deployment - IONIC 4
- Ionic 4 Crash Course with Heartstone API & Angular
- Ionic 4 Mega Course: Build 10 Real World Apps
Thanks!