Ionic

Ionic 5 Data Table with sort, filter and pagination (Demo + Source)

Share your learning

Ionic 5 data table with ionic grid, angular material and ngx-datatable with live demo and source code (git repo), you will get everything in this post.

In this tutorial we are going to learn following things,

  1. Table with Ionic Grid
  2. Angular Material Tables
  3. Ionic Table with ngx-datatable package

Live Demo

Table with Ionic grid

We can create a basic table with an ionic grid. As we know grid means combination of columns and rows which can help us to create a data table.

<ion-header [translucent]="true">
  <ion-toolbar [class]="tableHeader">
    <ion-title>
      Ionic Grid
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
  <ion-header collapse="condense">
    <ion-toolbar>
      <ion-title size="large">Tab 1</ion-title>
    </ion-toolbar>
  </ion-header>

  <ion-list>
    <ion-list-header lines="inset">
      <ion-label class="ion-text-bold">Change Table Header</ion-label>
    </ion-list-header>
    <ion-item>
      <ion-button (click)="changeTableHeader('dark')" color="dark">Dark</ion-button>
      <ion-button (click)="changeTableHeader('blue')" color="primary">Blue</ion-button>
      <ion-button (click)="changeTableHeader('red')" color="danger">Red</ion-button>
    </ion-item>

    <ion-list-header>
      <ion-label class="ion-text-bold">Change Table Theme</ion-label>
    </ion-list-header>
    <ion-item>
      <ion-select (ionChange)="changeTableTheme($event)" value="ion-border">
        <ion-select-option value="ion-border" selected>Basic Table</ion-select-option>
        <ion-select-option value="bootstrap-table">Bootstrap Table</ion-select-option>
      </ion-select>
    </ion-item>
   
  </ion-list>

  <ion-grid [class]="tableTheme">
    <ion-row [class]="tableHeader">
      <ion-col class="ion-text-bold"> Name </ion-col>
      <ion-col class="ion-text-bold"> Gender </ion-col>
      <ion-col class="ion-text-bold"> Company </ion-col>
    </ion-row>

    <ion-row *ngFor="let item of records">
      <ion-col>{{ item?.name }}</ion-col>
      <ion-col>{{ item?.gender }}</ion-col>
      <ion-col>{{ item?.company }}</ion-col>
    </ion-row>
  </ion-grid>

</ion-content>

We are using demo data from the following api.

https://swimlane.github.io/ngx-datatable/assets/data/company.json

We have created a dynamic table header and table theme. So, You can change the table header colors and table main theme in the given demo.

 import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-tab1',
  templateUrl: 'tab1.page.html',
  styleUrls: ['tab1.page.scss']
})
export class Tab1Page implements OnInit {

  records: any;
  tableHeader: string = 'header-dark';
  tableTheme: string = 'ion-border';

  constructor() {}

  ngOnInit() {
    fetch('https://swimlane.github.io/ngx-datatable/assets/data/company.json').then(res => res.json())
      .then(json => {
        console.log(json);
        this.records = json;
      });
  }

  changeTableHeader( color: string ) {
    this.tableHeader = 'header-'+color;
  }

  changeTableTheme( event: any ) {
    console.log(event);
    this.tableTheme = event.target.value;
  }

}

We have created some css for table styling as below,

.ion-text-bold {
    font-weight: bold;
}

.ion-border ion-row:first-child {
    border: 1px solid;
}

.ion-border ion-row:not(:first-child) {
    border-bottom: 1px solid;
    border-left: 1px solid;
    border-right: 1px solid;
}

.ion-border ion-row ion-col:not(:last-child) {
    border-right: 1px solid;
}

.bootstrap-table ion-row:nth-child(2n) {
 background: #d7d7d7;
 border-top: 1px solid #b3afaf;
 border-bottom: 1px solid #b3afaf;
}

.bootstrap-table ion-row {
    border-left: 1px solid #b3afaf;
    border-right: 1px solid #b3afaf;
}

.header-blue {
    background: #0000ff;
    --background: #0000ff;
    color: white;
}

.header-red {
    background: #b80303;
    --background: #b80303;
    color: white;
}

.header-dark {
    background: #080808;
    --background: #080808;
    color: white;
}

Angular Material Data table

Our second tab is the angular material table. You can check the official documentation of angular material table.

It has following features,

  1. Searching data in the table
  2. Sorting data
  3. Pagination of the table

It’s an amazing datatable, which is easy to integrate and it has enough features that are usually required by the datatable purpose.

Add angular material to your ionic 5 project

Run the following command to install the angular material to your existing project.

ng add @angular/material

Now we can import the required component to our ionic page. For example, we have used MatPaginator, MatTableDataSource, and MatSort to build this angular material data table.

The following process is required to use any angular material component.

  1. Import the component module to the page module file
  2. Import the component file to the page file

Example,

We have imported the MatTableModule, MatPaginatorModule, MatSortModule, MatInputModule file to the tab2.module.ts.

import { IonicModule } from '@ionic/angular';
import { RouterModule } from '@angular/router';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Tab2Page } from './tab2.page';
import { ExploreContainerComponentModule } from '../explore-container/explore-container.module';

import { Tab2PageRoutingModule } from './tab2-routing.module';
import {MatTableModule} from '@angular/material/table'; 
import { MatPaginatorModule } from '@angular/material/paginator';
import { MatSortModule } from '@angular/material/sort';
import {MatInputModule} from '@angular/material/input';

@NgModule({
  imports: [
    IonicModule,
    CommonModule,
    FormsModule,
    ExploreContainerComponentModule,
    Tab2PageRoutingModule,
    MatTableModule,
    MatPaginatorModule,
    MatSortModule,
    MatInputModule,
  ],
  declarations: [Tab2Page]
})
export class Tab2PageModule {}

Then we could use material components in our page file tab2.page.ts.

import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
import {MatSort} from '@angular/material/sort';

@Component({
  selector: 'app-tab2',
  templateUrl: 'tab2.page.html',
  styleUrls: ['tab2.page.scss']
})
export class Tab2Page implements AfterViewInit, OnInit {

  displayedColumns: string[] = ['name', 'gender', 'company'];
  records = new MatTableDataSource;

  length: number = 0;
  pageSize = 5;
  pageSizeOptions: number[] = [5, 10, 25, 100];

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

  constructor() {}
  
  ngOnInit() {
    
  }

  ngAfterViewInit() {
    fetch('https://swimlane.github.io/ngx-datatable/assets/data/company.json').then(res => res.json())
    .then(json => {
      this.records.data = json;
      this.length = this.records.data.length;
      this.records.paginator = this.paginator;
      this.records.sort = this.sort;
    });
  }

  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.records.filter = filterValue.trim().toLowerCase();

    if (this.records.paginator) {
      this.records.paginator.firstPage();
    }
  }

}

Ionic 5 data table with ngx-datatable package

The ngx-datatable package is also very useful for developing ionic tables with the same features as explained in the above angular material example.

Install the ngx-datatable package

Run the following npm command to install the ngx-datatable package.

npm i @swimlane/ngx-datatable --save

Import the ngx-datatable modules

Now, import the NgxDatatableModule to your module file, in our case it is tab3.module.ts.

import { IonicModule } from '@ionic/angular';
import { RouterModule } from '@angular/router';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Tab3Page } from './tab3.page';
import { ExploreContainerComponentModule } from '../explore-container/explore-container.module';

import { Tab3PageRoutingModule } from './tab3-routing.module';
import { NgxDatatableModule } from '@swimlane/ngx-datatable';

@NgModule({
  imports: [
    IonicModule,
    CommonModule,
    FormsModule,
    ExploreContainerComponentModule,
    RouterModule.forChild([{ path: '', component: Tab3Page }]),
    Tab3PageRoutingModule,
    NgxDatatableModule
  ],
  declarations: [Tab3Page]
})
export class Tab3PageModule {}

Import the ngx-datatable components

Then we can import and use ColumnMode, DatatableComponent to our page file which is tab3.page.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { ColumnMode, DatatableComponent } from '@swimlane/ngx-datatable';

@Component({
  selector: 'app-tab3',
  templateUrl: 'tab3.page.html',
  styleUrls: ['tab3.page.scss']
})
export class Tab3Page implements OnInit {

  rows = [];
  temp = [];

  columns = [{ prop: 'name' }, { name: 'Company' }, { name: 'Gender' }];
  @ViewChild(DatatableComponent) table: DatatableComponent;

  ColumnMode = ColumnMode;
  tableTheme: string = 'material';

  constructor() {}

  ngOnInit() {
    fetch('https://swimlane.github.io/ngx-datatable/assets/data/company.json')
      .then(res => res.json())
      .then(json => {
        this.temp = [...json];
        this.rows = json;
      });
  }

  updateFilter(event) {
    console.log(this.table);
    const val = event.target.value.toLowerCase();

    // filter our data
    const temp = this.temp.filter(function (d) {
      return (d.name.toLowerCase().indexOf(val) !== -1 || 
      d.gender.toLowerCase().indexOf(val) !== -1 ||
      d.company.toLowerCase().indexOf(val) !== -1) || !val;
    });

    // update the rows
    this.rows = temp;
    // Whenever the filter changes, always go back to the first page
    this.table.offset = 0;
  }

  changeTableTheme( event : any ) {
    this.tableTheme = event.target.value;
  }

}

We will also need the styling of ngx-datatable and for that we need to import ngx-datatable package’s css files to our global.scss file.

@import "~@swimlane/ngx-datatable/index.css";
@import "~@swimlane/ngx-datatable/assets/app.css";
@import "~@swimlane/ngx-datatable/themes/dark.css";
@import "~@swimlane/ngx-datatable/themes/bootstrap.css";
@import "~@swimlane/ngx-datatable/themes/material.css";
@import "~@swimlane/ngx-datatable/assets/icons.css";

After all of this, everything seemed perfect but one thing was wrong, that was table width and it was coming from the package css files.

So, let’s override that css in our style.scss file

/* ngx-datatable */.ngx-datatable,
.info {
  text-align: left;
  width: 95%;
  margin: 0 auto;
}

More Ionic Tutorial: Ionic 5 Shopping cart app with product listing, cart, product filtering, searching, sorting etc.

Hope you find this tutorial useful.

See you in the next learning journey.

Satpal

Recent Posts

How to Switch PHP Versions in XAMPP Easily: Managing Multiple PHP Versions on Ubuntu

Today we are going to learn about managing multiple PHP versions on ubuntu with xampp.…

1 year ago

How to Use Coding to Improve Your Website’s SEO Ranking?

Let's understand about how to use coding to improve your website's SEO. In today’s computerized…

1 year ago

Most Important Linux Commands for Web Developers

Let's understand the most important linux commands for web developers. Linux, as an open-source and…

1 year ago

Top 75+ Laravel Interview Questions Asked by Top MNCs

Today we are going to discuss top 75+ Laravel interview questions asked by top MNCs.Laravel,…

1 year ago

Mailtrap Integration for Email Testing with Laravel 10

Today we will discuss about the Mailtrap integration with laravel 10 .Sending and receiving emails…

1 year ago

Firebase Cloud Messaging (FCM) with Ionic 6: Push Notifications

Today we are going to integrate FCM (Firebase Cloud Messaging) push notifications with ionic application.Firebase…

1 year ago