Home » Angular DataTable Tutorial With Example

Angular DataTable Tutorial With Example

Last updated on December 29, 2020 by

In this tutorial, we will learn about the Angular DataTable step by step with examples. The DataTable is very essential & common functionality for most of the CMS.

Most of the DataTable plugins or NPM packages provide common functionalities like listing, filtering, searching, sorting, pagination, etc. If we create all these functionalities manually then it will take lots of time. Instead, we can use available Angular DataTable like jQuery DataTable, Angular DataTable, ngx-datatable, Angular Grid, ng2-table, ng2-smart-table, etc.

Here I am going to share how can you easily install those packages and use Angular DataTable to list out the data. Are you ready guys?

Let’s start.

Please note that this Angular DataTable demo has created in Angular 9 version

Angular DataTable Integration

01 Install Angular

We are presuming that you already have an Angular project set up on your machine either it’s a fresh installation or an existing Angular application. If you don’t have it then run the following command to install a new Angular application.

ng new ngDatatable

02 Install NPM Packages For Angular Datatable

Most of the Angular developers know the term “Packages”, if not then read the following definition:

A package is a piece of reusable code that can be dropped into any application and be used without any tinkering to add functionality to that code. You don’t need to know what is happening inside, only what the API for the class(es) are so that you can archive your goal

We don’t need to worry about the packages. It has some files and code inside it but one thing is for sure that it will solve our problem faster than we might think.

We hope you are now clear with the packages. Let’s go ahead.

Now, open your command-line tool and navigate it to the dataTableDemo directory where we just installed the project. We are using Git Bash as a command-line tool, you can use your own or you can install Git Bash from here as per your OS: https://git-scm.com/downloads

Run the following commands:

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

Now, wait until your installation finishes the process. If you are now done with the package installation then let’s move forward.

03 Update angular.json File

Now, go to the project folder and on the root, you can see the angular.json file open it. We now need to include the CSS and JS files in the angular.json file.

Under the "build" JSON object, you can find out the "styles" and "scripts" JSON array. Now, include the CSS and JS like below:

angular.json

....
"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"
]

04 Import Modules

Next, we need to import the necessary modules into our application. So that goes to the dataTableDemo/src/app directory and open the app.module.ts file and add the code as below:

src/app/app.module.ts

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

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

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

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

On the above code, we have imported DataTablesModule for the DataTables and HttpClientModule module for HTTP requests like POST, GET, etc.

Hope you are getting it. Let’s move on.

05 Update Component File

After importing the modules, we now need to add the code for fetching data from the backend API or external API, and other business logic. In the following example, we have added an external dummy API. You might have your own backend API.

So that goes to the dataTableDemo/src/app directory and open the app.component.ts file and add the code as below:

src/app/app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit{

  title = 'dataTableDemo';

  dtOptions: DataTables.Settings = {};
  posts: any;

  constructor(private http: HttpClient) {

    this.http.get('http://jsonplaceholder.typicode.com/posts')
      .subscribe(posts => {
        this.posts = posts;
    }, error => console.error(error));
  }

  ngOnInit(): void {
    this.dtOptions = {
      pagingType: 'full_numbers',
      pageLength: 5,
      processing: true
    };
  }
}

06 Update HTML File

We are heading towards the end of this tutorial. We now need to update the presentation login of our application. To do so go to the dataTableDemo/src/app directory and open the app.component.html file and add the code as below:

src/app/app.component.html

<div class="card-container">
    <h1 class="mb-5">Angular DataTable Tutorial With Example | ScratchCode.io</h1>

    <table datatable [dtOptions]="dtOptions" class="row-border hover">
        <thead>
            <tr>
                <th>ID</th>

                <th>Title</th>

                <th>Body</th>
            </tr>
        </thead>

        <tbody>
            <tr *ngFor="let post of posts">
                <td>{{ post.id }}</td>

                <td>{{ post.title }}</td>

                <td>{{ post.body }}</td>
            </tr>
        </tbody>
    </table>
</div>

Hurray! we are now done with all the steps. Now, run the below command to serve our application.

ng serve

Now, access the below URL in your favorite browser like below.

http://localhost:4200

Angular Datatable Output

You might be seeing same output as our for Angular Datatable.

angular datatables

Additionally, read our guide:

  1. AJAX PHP Post Request With Example
  2. Laravel DataTables Tutorial With Example
  3. How To Use The Laravel Soft Delete
  4. How To Add Laravel Next Prev Pagination
  5. Laravel Send Mail From Localhost
  6. How To Convert Word To PDF In Laravel
  7. How To Calculate Age From Birthdate
  8. How to Convert Base64 to Image in PHP
  9. Check If A String Contains A Specific Word In PHP
  10. Dynamically Populate A Select Field’s Choices In ACF
  11. How To Find Duplicate Records in Database
  12. Difference between del, remove and pop on lists
  13. How To Solve NPM Start Script Missing Error
  14. How To Declare A Global Variable in Vue
  15. Best Way to Resize Google reCAPTCHA

That’s it for now. We hope this article helped you to learn Angular DataTable with examples.

Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you in advance. 🙂 Keep Smiling! Happy Coding!

 
 

2 thoughts on “Angular DataTable Tutorial With Example”

  1. After research a couple of of the weblog posts on your website now, and I truly like your approach of blogging. I bookmarked it to my bookmark web site record and might be checking back soon. Pls try my site as well and let me know what you think.

    Reply

Leave a Comment

*

code