Ionic 5 List Sorting with Drag & Drop with Ion Reorder Tutorial

Ionic 5 Angular sortable item list tutorial; in this quick example, we will learn how to create a swipeable and sortable list in the Ionic 5 Angular application. Not just that, we will build the dynamic list for that we make the HTTP request and fetch the items from the server and display in the Ionic drag and drop list using the ion-reorder UI component.

A user-friendly user interface increases user engagement, essentials data should be displayed beautifully, and a list plays the crucial role in this voyage.

An extensive set of data can easily be placed in a list which user can scan and consume as per their need. This ionic dynamic list example tells you how to create the list similarly to create sorting list features in ionic using the default ion-reorder ion-reorder and ion-reorder-group directives from scratch.

Ionic 5 Angular Swipe, Sort and Reorder List Example

  • Step 1: Getting Started
  • Step 2: Set Up JSON Server
  • Step 3: Register HttpClientModule in Main Module
  • Step 4: Create Service
  • Step 5: Create Dynamic Sortable List
  • Step 6: Change Position of Reorder Handle
  • Step 7: Adding Custom Reorder Handle Icon
  • Step 8: Test Ionic App

Getting Started

To get started with this tutorial, make sure to set up the Ionic environment. Hence, install the Ionic CLI and create a new Ionic project.

npm install -g @ionic/cli

Then, create the latest Ionic Angular project:

ionic start ionic-sortable-list blank --type=angular

Enter into the project directory:

cd ionic-sortable-list

Set Up JSON Server

Type command in the command prompt and execute to install the json-server package from the npm repository.

npm install -g json-server

You need to create a server.json file in the ionic application’s root and, after that, add the following data into the server.json file.

{
  "users": [{
      "id": 1,
      "name": "Byron Carlson"
    }, {
      "id": 2,
      "name": "Sebastian Jacobs"
    }, {
      "id": 3,
      "name": "Cassandra Holland"
    }, {
      "id": 4,
      "name": "Henry Hanson"
    },
    {
      "id": 5,
      "name": "Chelsey Dietrich"
    }, {
      "id": 6,
      "name": "Kurtis Weissnat"
    }
  ]
}

Next, you have to start the json server.

json-server --watch server.json

Here is the endpoint you will get after the server successfully started.

Resources
http://localhost:3000/users

Home
http://localhost:3000

Register HttpClientModule in Main Module

To communicate with the server, you need to make HTTP requests, import the HttpClientModule in the main app.modulet.ts file.

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

@NgModule({
  declarations: [],
  entryComponents: [],
  imports: [
    HttpClientModule 
  ],
  providers: [],
  bootstrap: [],
})

export class AppModule {}

Create Service

In the subsequent step, generate the angular service to create the locus of reusable HTTP method code.

ng generate service list

Open list.service.ts file and insert the suggested code inside the file.

import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';

export class User {
  id: number;
  name: string;
}

@Injectable({
  providedIn: 'root'
})

export class ListService {

  API = 'http://localhost:3000/users';

  constructor(private http: HttpClient) { }

  getUsers(): Observable<User[]> {
    return this.http.get<User[]>(this.API)
      .pipe(
        tap(res => console.log(res)),
        catchError(this.handleError<User[]>('Get user', []))
      );
  }

  private handleError<T>(operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {
      console.error(error);
      console.log(`${operation} failed: ${error.message}`);
      return of(result as T);
    };
  }  

}

Create Dynamic Sortable List

Following code example get the data dynamically from the server, we also see how to create dynamic list and re-order list using swipe and drag and drop using ion-reorder-group and ion-reorder directives.

Reorder is a UI component provided by Ionic. Using reorder allows an item to change its position in a group of items list; we can drag and drop a list item to change its current order and position inside the group.

It should be used within an ion-reorder-group that leads us to drag and drop and swipe list item position, exclusively for list item reordering.

Update home.page.html file.

<ion-header [translucent]="true">
  <ion-toolbar>
    <ion-title>
      Ionic Drag and Drop List Example
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
  <ion-list>
    <ion-reorder-group (ionItemReorder)="reorderList($event)" disabled="false">

      <ion-item *ngFor="let user of UsersList">
        <ion-label>
          {{user.name}}
        </ion-label>
        <ion-reorder></ion-reorder>
      </ion-item>

    </ion-reorder-group>
  </ion-list>


  <ion-list text-center>
    <ion-button (click)="updatedList()" expand="block" color="success">
      Get Reordered List
    </ion-button>
  </ion-list>
</ion-content>

Update home.page.ts file.

import { Component } from '@angular/core';
import { ListService } from '../list.service';

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

export class HomePage {

  UsersList: any = [];

  constructor( private listService: ListService ) { 
    this.listService.getUsers().subscribe((res) => {
      this.UsersList = res;
    })    
  }

  reorderList(e) {
    console.log(`Item moved ${e.detail.from} to ${e.detail.to}`);
     let movedItem = this.UsersList.splice(e.detail.from,1)[0];
     this.UsersList.splice(e.detail.to, 0, movedItem)
     e.detail.complete();
  }

  updatedList() {
    console.table(this.UsersList);
  }  

}

Reorder list in Ionic

Change Position of Reorder Handle

Changing the reorder handle position is easy; you have to add the slot property and pass start similarly end attributes to change the reorder handle icon position.

<ion-list>
    <ion-reorder-group (ionItemReorder)="reorderList($event)" disabled="false">

        <ion-item *ngFor="let user of UsersList">
            <ion-label>
                {{user.name}}
            </ion-label>

            <!-- reorder handle position -->
            <ion-reorder slot="start"></ion-reorder>

        </ion-item>

    </ion-reorder-group>
</ion-list>

Change Position of Reorder Icon

Change Reorder Handle Icon

To change the default drag and drop the icon from the ionic list, you can define the ion-icon directive and pass the ionic icon’s name, make sure to declare ion-icon inside the ion-reorder attribute.

You can get hundreds of other icons; please checkout the ionicons website.

<ion-reorder-group (ionItemReorder)="reorderList($event)" disabled="false">

    <ion-item *ngFor="let user of UsersList">

        <ion-label>{{user.name}}</ion-label>

        <!-- Reorder custom icon -->
        <ion-reorder>
            <ion-icon name="arrow-redo-outline"></ion-icon>
        </ion-reorder>

    </ion-item>

</ion-reorder-group>

Change Reorder Handle Icon

Test Ionic App

We can install ionic lab package with dev dependency flag by executing provided command:

npm i @ionic/lab --save-dev

Eventually, you can run the app on the Android or iOS emulator:

ionic serve -l

Conclusion

The Ionic 5 dynamic swipe-able and sortable list tutorial is ended; In this quick guide, we profoundly described the ideal ways of adding a sortable list in the Ionic, angular app using the ion-reader UI component.

Not only but also explained how to set up a test server using the json-server npm package and showed you how to make an HTTP request to fetch the data from the server and display it in the list. A user can swipe, drag and drop and reorder list items in the ionic app; we reckon you liked this tutorial and share it with others.