Ionic 6 Angular Datatables with Pagination Tutorial

Ionic Angular Datatables tutorial; In this tutorial, you will learn how to create a dynamic data table in the Ionic Angular app using the npm ngx-datatable package.

The ngx-datatable is a handy package used to create a lightweight interactive data-table with powerful user-centric features to display data in tabular form. Using this ngx datatable package, we will integrate datatable in the Ionic app.

Similarly, we will explain step by step how to add datatables in ionic not only but also, and you will be given immaculate instruction to add pagination in ionic datatable to categorize extensive data set in smaller chunks.

A table is a classification of data in rows and columns or perhaps in a more heterogeneous formation.

Theoretically, Tables are mainly used to display comprehensive data in smaller pieces; apart from that, tables are also used in communication, research, and data analysis.

Ngx datatable is a feature-rich plugin, which comes with awesome traits, such as:

  • Handle large data sets ( Virtual DOM )
  • Expressive Header and Cell Templates
  • Horizontal & Vertical Scrolling
  • Column Reordering & Resizing
  • Client/Server side Pagination & Sorting
  • Cell & Row Selection ( Single, Multi, Keyboard, Checkbox )
  • Fixed AND Fluid height
  • Left and Right Column Pinning
  • Row Detail View
  • Decoupled theme’ing with included Google Material theme
  • Light codebase / No external dependencies
  • AOT Compilation Support
  • Universal Support
  • Intelligent Column Width Algorithms ( Force-fill & Flex-grow )
  • Integrated Pager

How to Integrate Datatables in Ionic 6 Angular App

  • Step 1: Install Ionic App
  • Step 2: Add and Set Up ngx-datatable Package
  • Step 3: Create Data Object
  • Step 4: Style Datatable
  • Step 5: Implement Data Table
  • Step 6: Start Development Server

Install Ionic App

Before we start developing the reusable datatable component angular, make sure you have the latest Ionic CLI installed.

npm install -g ionic@latest

Now, run the command to create a new blank Ionic, angular app:

ionic start ionic-datatable-example blank --type=angular

Move into the project:

cd ionic-datatable-example

Remove Type Errors

You have to remove strict type errors make sure to set “strictTemplates”: false in angularCompilerOptions in tsconfig.json file.

Add and Set Up ngx-datatable Package

To be eligible to use ngx-datatable in your ionic project, install it through node package manager:

npm i @swimlane/ngx-datatable

Ionic comes with a default home page, and we are using this page to display data in datatable, hence register the NgxDatatableModule, HttpClientModule and CUSTOM_ELEMENTS_SCHEMA in the HomePageModule class.

Hence, open and update home.module.ts file:

import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IonicModule } from '@ionic/angular';
import { FormsModule } from '@angular/forms';
import { HomePage } from './home.page';

import { HomePageRoutingModule } from './home-routing.module';

import { HttpClientModule } from '@angular/common/http';
import { NgxDatatableModule } from '@swimlane/ngx-datatable';


@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    HomePageRoutingModule,
    HttpClientModule,
    NgxDatatableModule
  ],
  declarations: [
    HomePage
  ],
  schemas: [
    CUSTOM_ELEMENTS_SCHEMA
  ]
})

export class HomePageModule {}

Create Data Object

In this step, we require to create a new file inside the src/assets directory, name it users.json. Similarly, add the user information that needs to be shown in the datatable.

Open and update src/assets/users.json file:

{
    "users": [
        {
          "id": 1,
          "name": "Leanne Graham",
          "username": "Bret",
          "email": "Sincere@april.biz"
        },
        {
          "id": 2,
          "name": "Ervin Howell",
          "username": "Antonette",
          "email": "Shanna@melissa.tv"
        },
        {
          "id": 3,
          "name": "Clementine Bauch",
          "username": "Samantha",
          "email": "Nathan@yesenia.net"
        },
        {
          "id": 4,
          "name": "Patricia Lebsack",
          "username": "Karianne",
          "email": "Julianne.OConner@kory.org"
        },
        {
          "id": 5,
          "name": "Chelsey Dietrich",
          "username": "Kamren",
          "email": "Lucio_Hettinger@annie.ca"
        },
        {
          "id": 6,
          "name": "Mrs. Dennis Schulist",
          "username": "Leopoldo_Corkery",
          "email": "Karley_Dach@jasper.info"
        },
        {
          "id": 7,
          "name": "Kurtis Weissnat",
          "username": "Elwyn.Skiles",
          "email": "Telly.Hoeger@billy.biz"
        },
        {
          "id": 8,
          "name": "Nicholas Runolfsdottir V",
          "username": "Maxime_Nienow",
          "email": "Sherwood@rosamond.me"
        },
        {
          "id": 9,
          "name": "Glenna Reichert",
          "username": "Delphine",
          "email": "Chaim_McDermott@dana.io"
        },
        {
          "id": 10,
          "name": "Clementina DuBuque",
          "username": "Moriah.Stanton",
          "email": "Rey.Padberg@karina.biz"
        },
        {
            "id": 11,
            "name": "Ava John",
            "username": "Ava_John",
            "email": "ava@gmail.com"
          },
          {
            "id": 12,
            "name": "Nosy Neighbour",
            "username": "Nosy_Neighbour",
            "email": "nosy@yahoo.com"
          },
          {
            "id": 13,
            "name": "John Doe",
            "username": "John_Doe",
            "email": "john@doe.me"
          }   
      ]    
}

Adding Datatable CSS

The ngx-datatable doesn’t come with predefined CSS, It gives you greater flexibility to add custom style into the table. However, we are adding the following CSS paths to spruce up the Ionic datatables.

Open and include index.css, material.scss and icons.css into home.page.scss file:

@import '~@swimlane/ngx-datatable/index.css';
@import '~@swimlane/ngx-datatable/themes/material.scss';
@import '~@swimlane/ngx-datatable/assets/icons.css';

Implement Data Table

The ion-content directive is used to create a datatable component; you can customize it to a great extent. It offers the innumerable option; for instance, you can set the table’s limit, define row height, and set header height, footer height, and many more.

To add more customization, please do check out the Ngx Datatable API.

Open and update home.page.html:

<ion-header [translucent]="true">
  <ion-toolbar>
    <ion-title>
      Ionic Datatable Example
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
    <ngx-datatable 
      class="material"
      [limit]="7" 
      [rows]="rows" 
      [rowHeight]="60" 
      [columns]="col"
      [columnMode]="'force'" 
      [sortType]="'multi'" 
      [headerHeight]="60" 
      [footerHeight]="60">
  </ngx-datatable>
</ion-content>

Update below code in app/home.module.ts file:

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

export interface USERS {
  users: string;
}

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

export class HomePage {
  public Users: USERS;
  public col: any;
  public rows: any;

  constructor(
    private httpClient: HttpClient
  ) {
    this.col = [
      { name: 'Name' },
      { name: 'Username' },
      { name: 'email' }
    ];

    this.httpClient.get<USERS>('../../assets/users.json')
      .subscribe((response) => {
        console.log(response)
        this.rows = response.users;
      });
  }
}

Start Development Server

At last you need to start the ionic development server and run the app to test the feature we created:

ionic serve

Datatables in Ionic Angular

Conclusion

Datatables works excellent in the larger display; nevertheless, it doesn’t work excellently in smaller devices. But if you are looking for a faster solution to implement datatables in ionic and at the same time wants to display data dynamically.

Consider using the ngx-datatable library; it will surely enhance the user experience and manage your data pretty well in a row and column format.