Datatables Plugin In Angular 7 Using .NET Core Web API - Part Two

Earlier, we developed the back-end logic for our application. If you have not seen it I recommend you to see that first from here.
 
Let’s start building our front-end application.
 
Open a new terminal in Visual Studio Code.
 
Datatables Plugin In Angular 7 Using .NET Core Web API
 
Type the following command to create a new project.
 
Datatables Plugin In Angular 7 Using .NET Core Web API
 
Open the newly created project from Visual Studio Code.
 
Datatables Plugin In Angular 7 Using .NET Core Web API
 
Choose the project from the explorer.
 
Datatables Plugin In Angular 7 Using .NET Core Web API
 
We will create the components for our application by typing these simple commands.
 
Datatables Plugin In Angular 7 Using .NET Core Web API
 
 
Datatables Plugin In Angular 7 Using .NET Core Web API
 
Create a folder named Models in the app folder.
 
Datatables Plugin In Angular 7 Using .NET Core Web API
 
Generate two TypeScript files as user.ts and search-criteria.ts.
 
Datatables Plugin In Angular 7 Using .NET Core Web API
 
Datatables Plugin In Angular 7 Using .NET Core Web API
 
Finally, install the DataTable plugins for Angular 7 by typing the following commands in the terminal.
  1. npm install jquery --save    
  2. npm install datatables.net --save    
  3. npm install datatables.net-dt --save    
  4. npm install angular-datatables --save    
  5. npm install @types/jquery --save-dev    
  6. npm install @types/datatables.net --save-dev    
  7. npm install bootstrap   
Open the user.ts file and add the below code in it. 
  1. export class User {    
  2.     ID: number;    
  3.     Name: string;    
  4.     Email: string;    
  5.     Company: string;    
  6.     ContactNumber: string;    
  7. }   
Here is the code for search-criteria.ts file.
  1. export interface SearchCriteria {  
  2.     isPageLoad: boolean;  
  3.     filter: string;  
  4. }  
Open the datatable-view.component.css file and add the following styles in it.
  1. .no-data-available {  
  2.     text-aligncenter;  
  3.   }  
  4.     
  5.   .ngHide {  
  6.       displaynone;  
  7.   }  
Open the datatable-view.component.html file and add the below styles in it.
  1. <br>    
  2. <div class="container">    
  3.   <h1>Users Table</h1>    
  4.   <br>    
  5.   <hr>    
  6.   <div>    
  7.     <div class="form-group">    
  8.       <label for="userName" class="control-label">Name</label>    
  9.       <input type="text" (keyup)="search()" class="form-control" id="userName" name="userName" [(ngModel)]="userName">    
  10.     </div>    
  11.   </div>      
  12.   <br>      
  13.   <div [class.ngHide]="searchCriteria.isPageLoad">    
  14.     <table datatable class="table table-striped" [dtOptions]="dtOptions" [dtTrigger]="dtTrigger">    
  15.       <thead>    
  16.         <tr>    
  17.           <td>ID</td>    
  18.           <td>Name</td>    
  19.           <td>Email</td>    
  20.           <td>Company</td>    
  21.           <td>Contact Number</td>    
  22.         </tr>    
  23.       </thead>    
  24.       <tbody *ngIf="users != null || users?.length != 0">    
  25.         <tr *ngFor="let user of users">    
  26.           <td style="width:2%">{{user.ID}}</td>    
  27.           <td style="width:10%">{{user.Name}}</td>    
  28.           <td style="width:30%">{{user.Email}}</td>    
  29.           <td style="width:40%">{{user.Company}}</td>    
  30.           <td style="width:18%">{{user.ContactNumber}}</td>    
  31.         </tr>    
  32.       </tbody>    
  33.       <tbody *ngIf="users == null || users?.length == 0">    
  34.         <tr>    
  35.           <td colspan="5" class="no-data-available">No data!</td>    
  36.         </tr>    
  37.       <tbody>    
  38.     </table>    
  39.   </div>    
  40. </div>   
Open the datatable-view.component.ts file and add this style into it.
  1. import { Component, OnInit, OnDestroy, ViewChild } from '@angular/core';    
  2. import { User } from '../models/user';    
  3. import { SearchCriteria } from '../models/search-criteria';    
  4. import { Subject, Observable, Subscription } from 'rxjs';    
  5. import { AppService } from '../app.service';    
  6. import { DataTableDirective } from "angular-datatables";    
  7. import { timer } from 'rxjs';    
  8. @Component({    
  9.   selector: 'app-datatable-view',    
  10.   templateUrl: './datatable-view.component.html',    
  11.   styleUrls: ['./datatable-view.component.css']    
  12. })    
  13. export class DatatableViewComponent implements OnInit {    
  14.   title = "app";    
  15.   users: User[];    
  16.   userName: string;    
  17.   searchCriteria: SearchCriteria = { isPageLoad: true, filter: "" };    
  18.   dtOptions: DataTables.Settings = {};    
  19.   dtTrigger: Subject<any> = new Subject();    
  20.   @ViewChild(DataTableDirective)    
  21.   dtElement: DataTableDirective;    
  22.   timerSubscription: Subscription;    
  23.   constructor(private appService: AppService) {}    
  24.   ngOnInit() {    
  25.     this.dtOptions = {    
  26.       pagingType: "full_numbers",    
  27.       pageLength: 10,    
  28.       serverSide: true,    
  29.       processing: true,    
  30.       searching: false,    
  31.       ajax: (dataTablesParameters: any, callback) => {    
  32.         dataTablesParameters.searchCriteria = this.searchCriteria;    
  33.         this.appService    
  34.           .getAllEmployeesWithPaging(dataTablesParameters)    
  35.           .subscribe(resp => {    
  36.             this.users = resp.data;    
  37.             callback({    
  38.               recordsTotal: resp.recordsTotal,    
  39.               recordsFiltered: resp.recordsFiltered,    
  40.               data: []    
  41.             });    
  42.           });    
  43.       },    
  44.       columns: [nullnullnullnull, { orderable: false }]    
  45.     };    
  46.     this.subscribeToData();    
  47.   }    
  48.   ngAfterViewInit(): void {    
  49.     this.dtTrigger.next();        
  50.   }    
  51.   rerender(): void {    
  52.     this.searchCriteria.isPageLoad = false;    
  53.     this.searchCriteria.filter = this.userName;    
  54.     this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {    
  55.       dtInstance.destroy();    
  56.       this.dtTrigger.next();    
  57.     });    
  58.   }    
  59.   search() {    
  60.     this.rerender();    
  61.   }    
  62.   ngOnDestroy(): void {    
  63.     this.dtTrigger.unsubscribe();    
  64.        
  65.     if (this.timerSubscription) {    
  66.       this.timerSubscription.unsubscribe();    
  67.     }    
  68.   }    
  69.   private refreshData(): void {    
  70.     this.rerender();    
  71.     this.subscribeToData();        
  72.   }    
  73.   private subscribeToData(): void {    
  74.     this.refreshData();    
  75.   }    
  76. }   
Create the app.service.ts file in the app folder. Then, add the following code into that.
  1. import { Injectable } from '@angular/core';  
  2. import { HttpClient } from "@angular/common/http"  
  3. import { User } from './models/user';  
  4. import { Observable } from 'rxjs';  
  5.   
  6. @Injectable()  
  7. export class AppService {  
  8.     private apiURL: string = 'http://localhost:49469/api/';  
  9.     constructor(private http: HttpClient) {  
  10.     }  
  11.     getAllEmployees(): Observable<User[]> {  
  12.         return this.http.get<User[]>(this.apiURL + 'DatatableApi');          
  13.     }  
  14.     getAllEmployeesWithPaging(dtParams: any): Observable<any> {  
  15.         return this.http.put(this.apiURL + 'DatatableApi', dtParams);          
  16.     }  
  17. }  
Open the app.component.html file and add this code into it.
  1. <app-datatable-view></app-datatable-view>  
Here is the code for app.module.ts file.
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import { AppRoutingModule } from './app-routing.module';  
  4. import { AppComponent } from './app.component';  
  5. import { DatatableViewComponent } from './datatable-view/datatable-view.component';  
  6. import { HttpClientModule } from '@angular/common/http';  
  7. import { DataTablesModule } from 'angular-datatables';  
  8. import { FormsModule } from "@angular/forms"  
  9. import { AppService } from './app.service';  
  10.   
  11. @NgModule({  
  12.   declarations: [  
  13.     AppComponent,  
  14.     DatatableViewComponent  
  15.   ],  
  16.   imports: [  
  17.     BrowserModule,  
  18.     HttpClientModule,  
  19.     DataTablesModule,  
  20.     FormsModule,  
  21.     AppRoutingModule  
  22.   ],  
  23.   providers: [AppService],  
  24.   bootstrap: [AppComponent]  
  25. })  
  26. export class AppModule { }  
Open the style.css file and add this line to it.
  1. .dataTables_empty {  
  2.     displaynone;  
  3. }  
Give the reference for datatable and bootstrap in angular.json file.
 
Datatables Plugin In Angular 7 Using .NET Core Web API
  1. "styles": [  
  2.               "src/styles.css",  
  3.               "node_modules/bootstrap/dist/css/bootstrap.min.css",  
  4.               "node_modules/datatables.net-dt/css/jquery.dataTables.css"  
  5.             ],  
  6.             "scripts": [  
  7.               "node_modules/jquery/dist/jquery.js",  
  8.               "node_modules/datatables.net/js/jquery.dataTables.js"  
  9.             ],  
That’s it. Now, run the project and your output will be like this.
 
Datatables Plugin In Angular 7 Using .NET Core Web API
 
Please give your valuable feedback/comments/questions about this article below. Please let me know how you like and understand this article and how I could improve it.
 
You can download the source code from here.


Similar Articles