Data tables were created to simplify the process of visualizing, grouping, querying, and sorting data. Often, a table is just a tabular form of data, nothing special. But a data table can provide multiple functions, including data sorting, data querying, data updating, paging, printing, data exporting, and so on.

Using data tables in a framework like Angular presents some complications because Angular constantly updates its code base.

  • Obsolete code. The Angular DataTables we will use in this article do not support older versions of Angular CLI (Angular 8 and below). Even older versions of Node and NPM use outdated code and therefore cannot use the service.
  • Configuration. Every developer will agree that some configurations are cumbersome, and Angular table configurations are no exception

What are Angular DataTables?

Angular DataTables is a library for building complex HTML tables using the jQuery DataTables plugin. Its configuration supports TypeScript and is optimized for Angular 2+.

Angular DataTables come in handy in the following situations.

  • You have a very large data set coming in from one or more API endpoints
  • You need to customize data sorting/filtering
  • You need to export and print data from a table

The functionality of Angular DataTables can be roughly divided into two groups: basic and advanced. As you can see, Angular DataTables also support some extended features.

The basic function

  • Load the data directly using AJAX calls
  • Options like column rendering in your Angular component
  • Render tables using custom functionsdtTrigger
  • Server-side processing (although you need to override the AJAX option)

Advanced features

  • User-defined filtering, including filtering by numbers, strings, and Boolean operations.
  • Separate column filtering, sorting data by column
  • Data table re-rendering
  • Multiple tables can be displayed simultaneously
  • Router links can be added to Angular components, and individual data instances can be displayed on new pages
  • Add pipes to the data table to convert the data to the format you want

The installation presents DataTables

Now let’s dive into installing and using Angular DataTables. First, we’ll install our Angular application and then install DataTables into it.

ng new angular-datatable
Copy the code

When Angular is installed, you can go to the terminal directory and install DataTables.

cd angular-datable

ng add angular-datatables
Copy the code

This will add jQuery and DataTables plug-ins to your angular.json file and to your application. When the installation is complete, you can import your spreadsheet module in app.module.ts and use it throughout the application.

// src/app/app.module.ts

import {DataTablesModule} from 'angular-datatables';

imports: [
  BrowserModule,
  AppRoutingModule,
  DataTablesModule,
],
Copy the code

Make API calls

We’ll use the JSONPlaceholderAPI to populate our tables to make Angular DataTables work.

To do this, we first add the HttpClient module to our app.module.ts file to make it available for HTTP requests in our service. We do this by importing it and calling it in the imports array.

// src/app/app.module.ts

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

imports: [
  BrowserModule,
  AppRoutingModule,
  DataTablesModule,
  HttpClientModule
],
Copy the code

Create an Angular service

We’ll create an Angular service that will communicate with our HTTP module to get data from our API. To generate this service, we will run the following command on the terminal.

ng generate service services/users/users

Copy the code

This will create a new file directory in our SRC /app folder containing our users.services.ts file.

-| Users/
    users.service.spec.ts
    users.services.ts
Copy the code

We can then import our HttpClient in our users.service.ts file.

// src/app/services/users/users.service.ts

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

constructor(private http: HttpClient) { }
Copy the code

Next, we add our function, which will get the user from the API link.

users() {
  this.http.get('https://jsonplaceholder.typicode.com/users');
}
Copy the code

Build a component

After creating the service, we regenerate it into a component called Users that will hold the data we got from the service we just created and display it in our HTML page. We will also use the Users component to create our tables and all the functionality.

To create a component, simply run the following command.

ng generate component components/users
Copy the code

Use the API

In our Users component, we will consume the API data obtained from the service we created and store it in an array named allUsers.

import { UsersService } from '.. /.. /services/users/users.service'; export class UsersComponent implements OnInit { allUsers: any = []; constructor(private service: UsersService) { } ngOnInit(): void { this.users(); } users(): void { this.service .users() .subscribe((response: any) => { this.allUsers = response.data; }); }}Copy the code

We then populate our users.component.html with the users we acquired.

<div class="container">
    <div class="card m-5 p-3">
        <div class="card-body">
            <table class="table table-bordered table-striped table-hover">
                <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Username</th>
                    <th>Email</th>
                    <th>Phone number</th>
                    <th>Address</th>
                </tr>
                </thead>
                <tbody>
                <tr *ngFor="let user of allUsers">
                    <td>{{ user.id }}</td>
                    <td>{{ user.name }}</td>
                    <td>{{ user.username }}</td>
                    <td>{{ user.email }}</td>
                    <td>{{ user.phone }}</td>
                    <td>{{ user.address.street }}, {{ user.address.city }}</td>
                </tr>
                </tbody>
            </table>
        </div>

    </div>
</div>
Copy the code

It will display something like this.

Now that this is all done, pry your fingers open as we delve into the use and manipulation of data tables

Add our data table

Because we already added our data table module to app.module.ts, we don’t have to import it in our component; We simply call it as a topic using RXJS.

// src/app/components/users/users.components.ts import {Subject} from 'rxjs'; . export class UsersComponent implements OnInit { dtOptions: DataTables.Settings = {}; dtTrigger: Subject<any> = new Subject<any>(); }Copy the code

Then we add our unsubscribe function to the AngularOnDestroy module.

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

export class UsersComponent implements OnInit, OnDestroy {
  ...
}

ngOnDestroy(): void {
  this.dtTrigger.unsubscribe();
}
Copy the code

This will reset the data table every time we leave the page connected to the component.

With this in mind, we will now add a data table in our Users function and a user table in our component HTML.

users(): void {
  this.service
      .users()
      .subscribe((response: any) => {
        this.allUsers = response;
        // initiate our data table
        this.dtTrigger.next();
      });
}
Copy the code
<table class="table table-bordered table-striped table-hover" datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger"> . </table>Copy the code

Filtering and paging have been added to the table, as you can notice in the image below.

Custom Filtering

Sometimes, we may want to search the data presented to the end user in our own way. Common examples include numeric range searches (between two numbers) and date range searches. Angular DataTables allow you to easily perform these custom searches.

Note that custom filtered documents in Angular DataTables are problematic, mainly because of TypeScript updates to Angular, so follow my example.

To enable custom filtering, we will first import an @ViewChild decorator that allows us to inject a reference to the element used in its template into the component class.

import {Component, OnInit, OnDestroy, ViewChild} from '@angular/core';
Copy the code

We then import the DataTableDirective into our component.

import {DataTableDirective} from 'angular-datatables';
Copy the code

We then refer to our DataTableDirective and assign it to a new variable, datatableElement. After that, we will create the Max and min variables that will provide the maximum and minimum numbers for our custom filtering.

Let’s start with quotes.

@ViewChild(DataTableDirective, {static: false})
datatableElement: any = DataTableDirective;
Copy the code
min: any = 0;
max: any = 0;
Copy the code

Next, we use custom functions in our ngOnInit to filter.

ngOnInit(): void { ... $.fn.dataTable.ext.search.push((settings: any, data: string[], dataIndex: any) => { const id = parseFloat(data[0]) || 0; // use data for the id column return (Number.isNaN(this.min) && Number.isNaN(this.max)) || (Number.isNaN(this.min) && id  <= this.max) || (this.min <= id && Number.isNaN(this.max)) || (this.min <= id && id <= this.max); }); }Copy the code

This will get the Max and min numbers, get the data, and then update the data table. Next, we create a function to filter the table by ID.

filterById(): void {
  this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => {
    dtInstance.draw();
  });
}
Copy the code

Now, when we exit the page, it will restart the data table.

ngOnDestroy(): void {
  ...
  $.fn.dataTable.ext.search.pop();
}
Copy the code

Once that’s done, we’ll update our users.ponents. HTML page and launch our filterById function.

<form (submit)="filterById()">
    <label>
        Min
        <input type="number" name="min" id="min" [(ngModel)]="min" />
    </label>
    <label>
        Max
        <input type="number" name="max" id="max" [(ngModel)]="max" />
    </label>
    <button class="btn btn-primary" type="submit">Filter by ID</button>
</form>
<br />
Copy the code

That’s it — we can use custom filtering by ID.

Button to expand

As mentioned above, Angular DataTables supports several extensions, one of which is the button extension. The button extension allows us to export and copy our table data into a file. This is especially useful when we want to share data without giving the application access.

To use the DataTables button extension, install its plug-in using the command below.

# If you want to export excel files
npm install jszip --save
# JS file
npm install datatables.net-buttons --save
# CSS file
npm install datatables.net-buttons-dt --save
# Typings
npm install @types/datatables.net-buttons --save-dev

Copy the code

Then add dependencies to the scripts and styles properties.

{ "projects": { "your-app-name": { "architect": { "build": { "options": { "styles": [ ... "node_modules/datatables.net-buttons-dt/css/buttons.dataTables.css" ], "scripts": [ ... "node_modules/jszip/dist/jszip.js", "node_modules/datatables.net-buttons/js/dataTables.buttons.js", "node_modules/datatables.net-buttons/js/buttons.colVis.js", "node_modules/datatables.net-buttons/js/buttons.flash.js", "node_modules/datatables.net-buttons/js/buttons.html5.js", "node_modules/datatables.net-buttons/js/buttons.print.js" ], . }Copy the code

We then include these configurations in our ngOnInit.

ngOnInit(): void {
  this.dtOptions = {
    // Declare the use of the extension in the dom parameter
    dom: 'Bfrtip',
  };
}
Copy the code

This is the result — buttons like copy, Excel, CSV, and print have been added.

There are many options available when it comes to customizing your spreadsheets. With a few tweaks, you can shape it to your specifications and it will bring perfect results for anything you build.

conclusion

That’s how we introduced Angular DataTables and their capabilities. We also applied it to an application, used some of its features, and explored button extensions. Due to Angular TypeScript updates, I made some changes to the original document. I hope this tutorial gives you a simple breakdown of how to use Angular DataTables in your Angular applications.

The postUsing Angular DataTables to build feature-rich tablesappeared first onLogRocket Blog.