Angular 9|8|7 DataTables, Sorting, Filter, Pagination using ngx-datatables with Ultimate features in Few Steps!

In this Angular 9 tutorial, we’ll learn how to install ngx-datatable package and build datatables in Angular application with Pagination, Sorting, Filters with examples.

Data tables are widely used in applications to show data sets with necessary features which are must to have for good user interactions like Pagination, Sorting by columns, Scrollings in horizontal and verticle directions, etc.

Application dealing with a large number of tabular data, it becomes very difficult to manage other details as well like the columns with custom templating and flexible styling.

In this post, we will discuss a very popular Datatable module ngx-datatable which is fully loaded with many required features and also very easy to use and manage. We’ll also, discuss some issues faced during sorting and tricks related to resetting or navigation of pagination from class component using the offset property.

Angular 9|8|7 DataTables, Sorting, Filter, Pagination using ngx-datatables with Ultimate features in Few Steps!

 

Let’s get started…

# Update Angular CLI

Run the following command to install the latest version of Angular CLI tool

$ npm i @angular/cli

 

# Create a new Angular project

Now by using the Angular CLI, we'll create a new Angular 9 project by running the ng command

$ ng new angular-datatables

Move to the project directory

$ cd angular-datatables

 

# Install Datatable Package

To use Datatables in Angular project, we'll install the ngx-datatable package by running following npm command in the terminal window

$ npm install @swimlane/ngx-datatable

 

# Update App Module

To use ngx-datatable in the application, we need to import the NgxDatatableModule in application module to provide its methods to implement Datatable in components.

Now open the app.module.ts file, and make following changes

// app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

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

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    NgxDatatableModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

 

# Import Theme Styles

The ngx-datatable package comes with three awesome themes including Dark, Bootstrap and Material theme.

There are two methods to import these themes in the Angular project:

Method 1) Import in the style.scss file

If you are using SCSS style of styling in Angular project then, you can simply import style files in the styles.scss file at the project root.

/* styles.scss */
/* You can add global styles to this file, and also import other style files */
@import '[email protected]/ngx-datatable/index.css';
@import '[email protected]/ngx-datatable/themes/material.scss';
@import '[email protected]/ngx-datatable/themes/dark.scss';
@import '[email protected]/ngx-datatable/themes/bootstrap.scss';
@import '[email protected]/ngx-datatable/assets/icons.css';
Method 2) Add in the angular.json file

We can also add themes in the angular.json file's styles array property as shown below

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

 

# How to use a theme in ngx-datatable?

As you can see we have added all the themes at once, you can change the theme of a ngx-datatable by adding a specific theme class on the <ngx-datatable> component:

class="material"

Angular 9|8|7 DataTables, Sorting, Filter, Pagination using ngx-datatables with Ultimate features in Few Steps!

class="bootstrap"

Angular 9|8|7 DataTables, Sorting, Filter, Pagination using ngx-datatables with Ultimate features in Few Steps!

class="dark"

Angular 9|8|7 DataTables, Sorting, Filter, Pagination using ngx-datatables with Ultimate features in Few Steps!

Now we have configured our Angular project to use NgxDatatables in components.

 

# Adding NgxDatatable

To implement the NgxDatatable we add ngx-datatable component with required and optional properties in the template file.

Open app.component.html file then add following HTML code with data table template with dummy data

<ngx-datatable class="material" [rows]="rows" [columnMode]="'force'" [headerHeight]="50" [footerHeight]="50"
  [rowHeight]="50" [scrollbarV]="true" [sorts]="[{prop: 'name', dir: 'desc'}]">

  <ngx-datatable-column name="Company">
    <ng-template let-row="row" ngx-datatable-cell-template>
      {{row.company}}
    </ng-template>
  </ngx-datatable-column>

  <ngx-datatable-column name="Name">
    <ng-template let-row="row" ngx-datatable-cell-template>
      {{row.name}}
    </ng-template>
  </ngx-datatable-column>

  <ngx-datatable-column name="Gender">
  </ngx-datatable-column>

</ngx-datatable>
Option Properties Used
[rows]: Data object is passed in the [rows] property using which datatable is build.
[columnMode]: This property id used to define the width of table columns using 'flex', 'fixed','force','standard'.
[headerHeight]: Height of table header
[footerHeight]: Height of table footer
[rowHeight]: Each row's height in the table
[scrollbarV]: Boolean to enable/disable verticle scroll
[scrollbarH]: Boolean to enable/disable horizontal scroll
[sorts]: Default sort column name in 'prop' and order by in the 'dir' with asc or desc

 

In the app.component.ts file, we will call dummy JSON data to build datatable

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent  implements OnInit {
  title = 'angular-datatables';


  rows = [];

  ngOnInit() {
    this.fetch((data) => {
      this.rows = data;
    });
  }

  fetch(cb) {
    const req = new XMLHttpRequest();
    req.open('GET', `http://swimlane.github.io/ngx-datatable/assets/data/company.json`);

    req.onload = () => {
      const data = JSON.parse(req.response);
      cb(data);
    };

    req.send();
  }

}

Angular 9|8|7 DataTables, Sorting, Filter, Pagination using ngx-datatables with Ultimate features in Few Steps!

 

# Issues with Implement Sorting with different column Header Name

To make sorting work properly the property name in the dataset object should match the column name. So it sometimes stops working if there is a mismatch in Column name and data property.

In this case, the Sorting on Company Name will not work

...
...
  <ngx-datatable-column name="Company Name">
    <ng-template let-row="row" ngx-datatable-cell-template>
      {{row.company}}
    </ng-template>
  </ngx-datatable-column>
...
...

as name attribute is having "Company Name" which is different from the company in {{row.company}}

So to resolve this we need to add prop attribute

Sorting will work fine

...
...
  <ngx-datatable-column name="Company Name" prop="company">
    <ng-template let-row="row" ngx-datatable-cell-template>
      {{row.company}}
    </ng-template>
  </ngx-datatable-column>
...
...

Note: prop value is case sensitive so it should match exactly with a data property.

# How to Disable Sorting on a Single Column

In some columns of a table like an index number or serial number we may not need the sorting faster. In that case, just add [sortable]="false" on <ngx-datatable-column> to disable sorting on a single column.

# How to Change/ Reset pagination or go to a specific page in ngx-datatables?

During some operation, we may want to reset the pagination or come back to page 1. For that, we need to add a template reference variable on the <ngx-datatable>. As shown below we added the #myTable variable

<ngx-datatable #myTable class="material" [rows]="rows" [columnMode]="'force'" [headerHeight]="50" [footerHeight]="50"
  [rowHeight]="50" [scrollbarV]="true" [sorts]="[{prop: 'name', dir: 'desc'}]">

...
...

</ngx-datatable>

Now, in the component class, we will get the reference of this data table using #myTable in combination with @ViewChild of type DatatableComponent. After that just set offset value to 0which means page number 1.

 ...
...

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

@Component({
  selector: 'app-datatable',
  templateUrl: './datatable.component.html'
})
export class DatatableComponent implements OnInit {

  @ViewChild('myTable') table: DatatableComponent;


  ngOnInit() {
    // for page number 1 as offset starts with 0
    this.table.offset = 0;
  }

...
...

by using offset you can change/ reset default pagination page number in the ngx-datatable

 

# Adding Filter Search on ngx-datatable

To enable filter search we need to make some changes in the template and class

Step 1) Add Input control with  (keyup)="updateFilter($event)" key event handler

<input type="text"  placeholder="Type to filter the name column..." (keyup)="updateFilter($event)" />

Step 2) Add template reference variable #myFilterTable (anything you want) on the ngx-datatable .

 

Step 3) Update class file with updateFilter() method which we called on keyup event. Also, we need a temp variable to keep actual data loaded in the table before any filter action. Check highlighted changes for filter functionality in the class below:

export class AppComponent {
  title = 'angular-ngx-datatable-tutorial';

  temp = [];
  rows = [];

  @ViewChild(DatatableComponent) myFilterTable: DatatableComponent;

  ngOnInit() {
    this.fetch(data => {
      // cache our list
      this.temp = [...data];

      // push our inital complete list
      this.rows = data;
    });
  }

  fetch(cb) {
    const req = new XMLHttpRequest();
    req.open('GET', `http://swimlane.github.io/ngx-datatable/assets/data/company.json`);

    req.onload = () => {
      const data = JSON.parse(req.response);
      cb(data);
    };

    req.send();
  }

  updateFilter(event) {
    const val = event.target.value.toLowerCase();

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

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

}

Here we are only filtering the Name column in the updateFilter() method. To check the filter on all or selected columns see this tutorial.

Angular 9|8|7 DataTables, Sorting, Filter, Pagination using ngx-datatables with Ultimate features in Few Steps!

 

Conclusion: So, in the above post, we implemented Datatables in Angular application using one of the most popular datatable packages ngx-datatable. The ngx-datatable supports a number of powerful features including freeze columns, table column filters, server-side pagination etc. You can build an awesome table using this package module.

Subscribe
Notify of
guest
1 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
rinku

very nice