How to Use ngx-datatable Component to create Data Tables in Ionic 4

A complete step by step Ionic 4 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.

Table of Contents

  • Installing Cordova
  • Setting Up Ionic 4 Camera App
  • Adding Platform in Ionic
  • Install Ionic Cordova and Native Camera Plugin
  • Importing Camera Plugin in App Module
  • Using Camera Plugin in Ionic 4 Component
  • Test Camera App in Browser
  • Conclusion

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
cd ionic-tables-app

Enter inside the project folder.

cd ./ionic-tables-app

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 --save

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 4

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 app.module.ts file and add the following code to make the HTTP request.

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

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

export class AppModule { }

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 add CSS and icons to ngx-datatable in Ionic 4, It will help us to sort out ‘ngx-datatable style not working’ issue.

First, go to assets folder and create styles > ngx-datatable folder inside the assets folder.

Next, copy ngx-datatable’s theme’s CSS files from the following paths.

# node_modules > @swimlane > ngx-datatable > index.css
# node_modules > @swimlane > ngx-datatable > themes > bootstrap.css
# node_modules > @swimlane > ngx-datatable > themes > dark.css
# node_modules > @swimlane > ngx-datatable > themes > material.css

Copy the fonts folder and icons.css from the following path…

# node_modules > @swimlane > ngx-datatable > assets > fonts

# node_modules > @swimlane > ngx-datatable > assets > icons.css

Next, paste data table theme files, fonts folder and icons.css file inside the following path.

# app > assets > styles > ngx-datatable

Now, change the name of these data table files as given below.

_index.css
_bootstrap.css
_dark.css
_icons.css
_material.css

Next, go to app/assets/styles/ngx-datatable/_icons.css file and update data-table @font-face path as given below.

@font-face {
  font-family: 'data-table';
  src: url('./fonts/data-table.eot');
  src: url('./fonts/data-table.eot?#iefix') format('embedded-opentype'), 
    url('./fonts/data-table.woff') format('woff'),
    url('./fonts/data-table.ttf') format('truetype'), 
    url('./fonts/data-table.svg#data-table') format('svg');
  font-weight: normal;
  font-style: normal;
}

Then, we will add the following data table theme paths inside the global CSS file. Add the following path inside the global.scss file.

/*
 * App Global CSS
 * ----------------------------------------------------------------------------
 * Put style rules here that you want to apply globally. These styles are for
 * the entire app and not just one component. Additionally, this file can be
 * used as an entry point to import other CSS/Sass files to be included in the
 * output CSS.
 * For more information on global stylesheets, visit the documentation:
 * https://ionicframework.com/docs/layout/global-stylesheets
 */

/* Core CSS required for Ionic components to work properly */
@import "~@ionic/angular/css/core.css";

/* Basic CSS for apps built with Ionic */
@import "~@ionic/angular/css/normalize.css";
@import "~@ionic/angular/css/structure.css";
@import "~@ionic/angular/css/typography.css";
@import '~@ionic/angular/css/display.css';

/* Optional CSS utils that can be commented out */
@import "~@ionic/angular/css/padding.css";
@import "~@ionic/angular/css/float-elements.css";
@import "~@ionic/angular/css/text-alignment.css";
@import "~@ionic/angular/css/text-transformation.css";
@import "~@ionic/angular/css/flex-utils.css";

/* NGX Datatable CSS */
@import '~assets/styles/ngx-datatable/_index.css';
@import '~assets/styles/ngx-datatable/_dark.css';
@import '~assets/styles/ngx-datatable/_material.css';
@import '~assets/styles/ngx-datatable/_bootstrap.css';
@import '~assets/styles/ngx-datatable/_icons.css';

We have added the styling in Ionic’s data table app. Now, we need to import ViewEncapsulation and register the encapsulation: ViewEncapsulation in the @component in Ionic component.

We are doing it to remove the unnecessary attribute [_ngcontent-c1], It is a classed and automatically added by Angular. This stops us styling the ngx-datatable.

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

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

export class HomePage {

}

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.module.ts 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 4 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 4 Data Tables tutorials, In this tutorial we learned how to use ngx-datatable component to create the data tables, we also looked at how to fetch the data externally and display in the Ionic tables. Get the complete code of this tutorial on this GitHub repository.

#Ionic #Angular #webdev

How to Use ngx-datatable Component to create Data Tables in Ionic 4
306.00 GEEK