Data Tables in Angular

Rana Hasnain Khan Dec 08, 2021
  1. Data Tables in Angular
  2. Convert JSON to Data Tables in Angular
Data Tables in Angular

We will introduce how to use data tables and convert JSON responses into data tables in Angular.

Data Tables in Angular

There is a prebuilt library of angular-datatables that we can use to show complex data tables in Angular.

We can easily install it by using the following command:

# terminal
ng add angular-datatables

Or we can install it manually using npm:

# terminal
npm install jquery --save
npm install datatables.net --save
npm install datatables.net-dt --save
npm install angular-datatables --save
npm install @types/jquery --save-dev
npm install @types/datatables.net --save-dev

And after that, we need to add the dependencies in the scripts and styles attributes to the angular.json file.

# angular
"projects": {
    "your-app-name": {
      "architect": {
        "build": {
          "options": {
            "styles": [
              "node_modules/datatables.net-dt/css/jquery.dataTables.css"
            ],
            "scripts": [
              "node_modules/jquery/dist/jquery.js",
              "node_modules/datatables.net/js/jquery.dataTables.js"
            ],
            ...
          }
}

Now, we need to import DataTablesModule at the appropriate level of our app.

# angular
import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";

import { DataTablesModule } from "angular-datatables";

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

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

Convert JSON to Data Tables in Angular

We can use the following example if we want to convert a JSON response into DataTables.

We need to add the following code to app.component.ts.

# angular
import { AfterViewInit, VERSION, Component, OnInit, ViewChild } from '@angular/core';
import { DataTableDirective } from 'angular-datatables';
import { Subject } from 'rxjs';
import 'rxjs/add/operator/map';
import { HttpParams, HttpClient, HttpHeaders } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
})
export class AppComponent implements OnInit, AfterViewInit {
  version = 'Angular: v' + VERSION.full;
  @ViewChild(DataTableDirective)
  datatableElement: DataTableDirective;
  dtOptions: DataTables.Settings = {};
  persons: any = [];
  // We use this trigger because fetching the list of persons can be quite long,
  // thus we make sure the data gets fetched before rendering
  dtTrigger: Subject<any> = new Subject();

  constructor(private http: HttpClient) { }

  ngOnInit(): void {
    const dataUrl = 'https://raw.githubusercontent.com/Inventico-Sol/test-json/main/data.json';

    this.http.get(dataUrl)
      .subscribe(response => {
        setTimeout(() => {
          this.persons = response.data;
          console.log(response);
          // Calling the DT trigger to manually render the table
          this.dtTrigger.next();
        });
      });

  }

  ngAfterViewInit(): void {

    this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => {
      dtInstance.columns().every(function () {
        const that = this;
        $('input', this.footer()).on('keyup change', function () {
          if (that.search() !== this['value']) {
            that
              .search(this['value'])
              .draw();
          }
        });
      });
    });

  }
}

Then, we must add the following code to app.component.html.

# angular
{{ version }}
<table
  datatable
  [dtOptions]="dtOptions"
  [dtTrigger]="dtTrigger"
  class="row-border hover"
>
  <thead>
    <tr>
      <th>ID</th>
      <th>Name</th>
      <th>Age</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let person of persons">
      <td>{{ person.id }}</td>
      <td>{{ person.name }}</td>
      <td>{{ person.age }}</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <th><input type="text" placeholder="Search ID" name="search-id" /></th>
      <th>
        <input
          type="text"
          placeholder="Search first name"
          name="search-first-name"
        />
      </th>
      <th>
        <input
          type="text"
          placeholder="Search last name"
          name="search-last-name"
        />
      </th>
    </tr>
  </tfoot>
</table>

Output:

data tables in Angular

Rana Hasnain Khan avatar Rana Hasnain Khan avatar

Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.

LinkedIn