Create Data Tables with Ionic 7 and ngx-datatable

Last Updated on by in Ionic
A complete step by step Ionic Data Table tutorial, create a data table in an Ionic / Angular app and learn how to show relevant information in tabular form using the ngx-datatable plugin.ngx-datatable dark

The purpose of this post is to teach you how to create data tables in the Ionic app quickly. We will take some dummy data and present that beautifully in an interactive tabular format using Angular’s ngx-datatable component.

Data tables are advantageous in showing the relevant information in an orderly manner. The nature of the Data Table is such, and it helps you scan the information more quickly, which leads you to make faster decisions.

Data comparison, visualization, and analysis become so easy due to its rows and columns pattern that accommodates users to examine the necessary data faster.

A useful and attractive data table is created with Rows / Columns, Pagination, Edit mode, Mode of actions and Expanded view components.

Getting Started

Install the latest version of Ionic CLI on your system.

npm install -g ionic@latest

Generate the new ionic project name it ionic-tables-app.

ionic start ionic-tables-app blank --type=angular

Enter inside the project folder.

cd ionic-tables-app

Run the below command to add the native core package.

npm install @ionic-native/core --legacy-peer-deps

Disable Strict Type Errors

To avoid TypeScript compiling issues, we just need to open tsconfig.json file:

First, set below property under “compilerOptions” property.

"compilerOptions": {
    "strictPropertyInitialization": false,
    "skipLibCheck": true
    ...
}

Secondly, add given props under “angularCompilerOptions”.

"angularCompilerOptions": {
    "strictTemplates": false,
    ...
}

Run the Ionic app in the browser.

ionic serve

Install and Configure ngx-datatable

Install the ngx-datatable component using following command.

npm install @swimlane/ngx-datatable --legacy-peer-deps

Once the data table plugin is installed, then import and declare NgxDatatableModule in app/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 { RouterModule } from '@angular/router';
import { HomePage } from './home.page';

import { NgxDatatableModule } from '@swimlane/ngx-datatable';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    RouterModule.forChild([
      {
        path: '',
        component: HomePage
      }
    ]),
    NgxDatatableModule,
  ],
  declarations: [HomePage],
  schemas: [CUSTOM_ELEMENTS_SCHEMA]
})

export class HomePageModule { }

If you are getting the given below error, then import the `CUSTOM_ELEMENTS_SCHEMA` and declare `schemas: [CUSTOM_ELEMENTS_SCHEMA]` in your Ionic’s page.module.ts file.

# CUSTOM_ELEMENTS_SCHEMA Error in Ionic

If 'xx-xxxx' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" 
to the '@NgModule.schema' of this component to suppress this message.

Since, we are externally importing the data in the table, so we need to import and register the HttpClientModule in AppModule file.

Go to home.module.ts file and add the following code to make the HTTP request.

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 {}

We have successfully configured the data table module in our ionic app module, move to the next step, and add some dummy data to show in the Ionic table.

Adding Dummy Data

We are going to create some dummy movies data in JSON format, this data will be displayed in the Ionic tables.

Create a file in the src/assets folder name it movies.json and add the following code inside of it.

{
    "movies": [
        {
            "name": "Escape Room",
            "company": "Columbia Pictures",
            "genre": "Horror"
        },
        {
            "name": "Rust Creek",
            "company": "IFC Films",
            "genre": "Drama"
        },
        {
            "name": "American Hangman",
            "company": "Hangman Productions",
            "genre": "Thriller"
        },
        {
            "name": "The Upside",
            "company": "STX Entertainment",
            "genre": "Comedy"
        },
        {
            "name": "Replicas",
            "company": "Entertainment Studios",
            "genre": "Sci-Fi"
        },
        {
            "name": "After Darkness",
            "company": "Grindstone Group",
            "genre": "Drama"
        },
        {
            "name": "Glass",
            "company": "Universal Pictures",
            "genre": "Superhero"
        },
        {
            "name": "Close",
            "company": "Netflix",
            "genre": "Action"
        },
        {
            "name": "The Final Wish",
            "company": "BondIt Capital",
            "genre": "Horror"
        },
        {
            "name": "Serenity",
            "company": "Aviron Pictures",
            "genre": "Drama"
        },
        {
            "name": "Miss Bala",
            "company": "Columbia Pictures",
            "genre": "Thriller"
        },
        {
            "name": "Velvet Buzzsaw",
            "company": "Netflix",
            "genre": "Comedy"
        }
    ]
}

Given above is the basic data, It is a simple list of Movies with the genre type and the production houses which released these movies.

Adding Style to ngx-datatable in Ionic

In this step, we will learn how to easily include CSS and icons to ngx-datatable in Ionic.

It will help us to sort out ‘ngx-datatable style not working’ issue.

Add index.css, material.scss and icons.css into angular.json file as suggested below:

"styles": [
      "./node_modules/@swimlane/ngx-datatable/index.css",
      "./node_modules/@swimlane/ngx-datatable/themes/material.css",
      "./node_modules/@swimlane/ngx-datatable/assets/icons.css",
      "src/theme/variables.scss",
      "src/global.scss"
  ],

Now, you are completely ready to add the styling in ngx-datatable component.

Creating Data Table

Now, we will write the logic to fetch the external data using the Angular’s HttpClient Service and display that data inside the data tables using ngx-datatable component.

Open home.page.ts file and add the following code in it.

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

export interface Data {
  movies: string;
}

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

export class HomePage {
  public data: Data;
  public columns: any;
  public rows: any;

  constructor(
    private http: HttpClient
  ) {
    this.columns = [
      { name: 'Name' },
      { name: 'Company' },
      { name: 'Genre' }
    ];

    this.http.get<Data>('../../assets/movies.json')
      .subscribe((res) => {
        console.log(res)
        this.rows = res.movies;
      });
  }
}

As far as the above code is concerned, we used a Data interface class to fetch the data using HttpClient’s GET method. It returns an observable which we subscribed to and assign it to rows in the Ionic view.

Add the following code in app/home.page.html file.

<ion-header>
  <ion-toolbar>
    <ion-title>NGX Data Table</ion-title>
  </ion-toolbar>
</ion-header>


<ion-content>
  <div class="ion-padding">

    <!-- Theme classes dark, material, bootstrap -->
    <ngx-datatable 
      class="material"
      [limit]="8" 
      [rows]="rows" 
      [rowHeight]="50" 
      [columns]="columns"
      [columnMode]="'force'" 
      [sortType]="'multi'" 
      [headerHeight]="50" 
      [footerHeight]="50">
    </ngx-datatable>

  </div>
</ion-content>

To get the data in the data table, we used the following properties with the ngx-datatabel directive.
limit: Sets the number of items to display in the data table.
rows: Renders the data in the rows with the help of the component class.
rowHeight: Sets the height of the table rows.
columns: Renders the names of the columns from the component class property.
columnMode: Either flex or force – Force prop maintains the distance between columns.
sorttype: Sorts data on multiple columns.
headerHeight: Sets the height of the table header.
footerHeight: Sets the height of the table footer.

Ionic Data Table

You can change the data table theme using one of the following class with ngx-datatable attribute.

  • material
  • dark
  • bootstrap

Conclusion

We have completed Ionic Data Tables tutorial.

In this quick guide, we have learned how to use ngx-datatable component to create the data tables. Apart from that, we also looked at how to fetch the data externally and display in the Ionic tables.