Ionic 3 and Angular 5 Search and Sort List of Data

by Didin J. on Dec 18, 2017 Ionic 3 and Angular 5 Search and Sort List of Data

Step by step tutorial of Ionic 3, Angular 5 search and Sort List of Data with working example

A comprehensive step by step tutorial of Ionic 3, Angular 5  and Sort List of Data with a working example. Almost every Ionic 3 or Angular 5 application that has a list need to searching and sorting the list. We will build the searching and sorting of the list of data that loaded to an array. We will use the same API call as the previous tutorial for load Country list. The main purpose of this tutorial is to populate existing data using Angular pipes. There are ready to use Angular pipes modules, but we will create our own from scratch.

Jumps to the steps:

The following tools, frameworks, and modules are required for this tutorial:

  1. Node.js (use recent recommended version)
  2. Ionic 3 CLI
  3. Angular 5
  4. IDE or Text Editor
  5. Terminal or Node.js Command Line

Before starting with the main steps, make sure the above tools, frameworks, and modules are up to date. For Node.js you check and compare your local version with the recent recommended on the official site https://nodejs.org/. To check your local version type this command on the terminal or Node.js command line.

node -v

Here's our latest version.

v8.9.3

Now, update the Ionic 3 version by type this command.

sudo npm i -D -E ionic@latest


Create a New Ionic 3 Angular 5 Application

To create a new Ionic 3 and Angular 5 application, type this command.

ionic start ionic-search blank

If there's a question like below, just type `N` because we will not use Cordova right now.

Would you like to integrate your new app with Cordova to target native iOS and
 Android? (y/N) N

The Ionic 3 app created and automatically installing Node modules. Now, go to the newly created Ionic 3 app folder.

cd ./ionic-search

As usual, to check app just run the app in the browser after type this command.

ionic serve -l

You will see the page below in the browser if everything still good.

Ionic 3 and Angular 5 Search and Sort List of Data - Ionic Blank Page


Get All Country Data from REST API

As we said at the beginning of this tutorial, we have to load all Country data from free API to an array. Before populating any data from API, we have to add `HttpClientModule` to `app.module.ts`. Modify `src/app/app.module.ts` then add this import of HttpClientModule (@angular/common/http).

import { HttpClientModule } from '@angular/common/http';

Also add `HttpClientModule` to `@ngModule` imports.

imports: [
  BrowserModule,
  HttpClientModule,
  IonicModule.forRoot(MyApp)
],

The `HttpClient` is ready now to use for calling REST API. Next, type this command to generate a service or provider.

ionic g provider RestApi

Next, modify `src/providers/rest-api/rest-api.ts` then add these imports of RxJS Observable, map, and catchError (RxJS Operators).

import { Observable } from 'rxjs/Observable';
import { map, catchError } from 'rxjs/operators';

You will see in the provider file there's `HttpClient` already imported and injected into the constructor. Now, add string variable for URL before the constructor.

private apiUrl = 'https://restcountries.eu/rest/v2/all';

Create a function for getting Countries data from REST API.

getCountries(): Observable<string[]> {
  return this.http.get(this.apiUrl).pipe(
    map(this.extractData),
    catchError(this.handleError)
  );
}

Also, create functions for handling and extract response and catch the error.

private extractData(res: Response) {
  let body = res;
  return body || {};
}

private handleError (error: Response | any) {
  let errMsg: string;
  if (error instanceof Response) {
    const err = error || '';
    errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
  } else {
    errMsg = error.message ? error.message : error.toString();
  }
  console.error(errMsg);
  return Observable.throw(errMsg);
}

Next, modify `src/pages/home/home.ts` then add this import.

import { RestApiProvider } from '../../providers/rest-api/rest-api';

Inject that class name to the constructor, so it will look like this.

constructor(public navCtrl: NavController, public rest: RestApiProvider) {}

Add these variables for holds Countries data and error message.

countries: string[];
errorMessage: string;

Now, create a function for calling get countries from REST API provider and set the response to countries variable.

getCountries() {
  this.rest.getCountries()
     .subscribe(
       countries => this.countries = countries,
       error =>  this.errorMessage = <any>error);
}

To load that function when the page load, call `getCountries()` function inside this load function.

ionViewDidLoad() {
  this.getCountries();
}

Now, display the data in HTML by modifying `src/pages/home/home.html` then replace all tags with this.

<ion-header>
  <ion-navbar>
    <ion-title>
      Country List
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <ion-list>
    <ion-item *ngFor="let c of countries">
      <ion-avatar item-left>
        <img src="{{c.flag}}">
      </ion-avatar>
      <h2>{{c.name}}</h2>
      <p>Capital: {{c.capital}}, Region: {{c.region}}</p>
    </ion-item>
  </ion-list>
</ion-content>

Run again the app in the browser, you will see the list of all countries.

Ionic 3 and Angular 5 Search and Sort List of Data - List of Countries


Create Pipes for Search and Sort

For searching and sorting countries data, simply just create the pipes. Type this command to generate a pipe.

ionic g pipe search
ionic g pipe sort

That command will create `pipes` folder, search and sort folders and files. Now, modify `src/pipes/search/search.ts` then replace the default `transform` function with this.

transform(items: any[], terms: string): any[] {
  if(!items) return [];
  if(!terms) return items;
  terms = terms.toLowerCase();
  return items.filter( it => {
    return it.name.toLowerCase().includes(terms); // only filter country name
  });
}

Next, modify `src/pipes/sort/sort.ts` then replace default transform function with this.

transform(array: Array<string>, args?: any): Array<string> {
  return array.sort(function(a, b){
    if(a[args.property] < b[args.property]){
        return -1 * args.order;
    }
    else if( a[args.property] > b[args.property]){
        return 1 * args.order;
    }
    else{
        return 0;
    }
  });
}


Implementing Search and Sort Pipes on the Page

To implements, search and sort pipes, first, register that pipes in `app.module.ts`. Modify `src/app/app.module.ts` then add these imports.

import { SearchPipe } from '../pipes/search/search';
import { SortPipe } from '../pipes/sort/sort';

Then add in `@ngModule` declarations array.

declarations: [
  MyApp,
  HomePage,
  SearchPipe,
  SortPipe
],

Next, modify `src/pages/home/home.html` then add search box component and a button for sorting.

<ion-searchbar [(ngModel)]="terms"></ion-searchbar>
<button ion-button type="button" (click)="sort()">Sort</button>

Add the filter into list item array.

<ion-item *ngFor="let c of countries | search : terms | sort: {property: column, order: order}">

Modify `src/pages/home/home.ts` then add these variables before the constructor.

descending: boolean = false;
order: number;
column: string = 'name';

Finally, add the function for sorting.

sort(){
  this.descending = !this.descending;
  this.order = this.descending ? 1 : -1;
}

Now, you can test sorting and searching by run again the app in the browser.

Ionic 3 and Angular 5 Search and Sort List of Data - List with search and sort

That's it, 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:

Thanks!

Loading…