Angular Material Datatable With Angular 6 - Part Two

Introduction
 
In this second part of the article on Angular Material Datatable, we are going to learn how to implement searching, filtering, and one combined example in which we will implement all of the functionality using Angular Material Datatable.
 
I would recommend you to go through the first part of this article, where I have explained the basic configurations, for that just follow the given link.
In the first part of the series, we have learned different functionalities of Angular Material Datatable. 
  • Simple Datatable
  • Data table With Pagination
  • Data table With Sorting
In this part, we will continue learning more functionality. So, let's implement it one by one.
 
Data table with filtering 
 
Filtering makes it easy to search the record from the tons of available records, we just need to pass the search string and based on the search string, we will get the matching records. 
 
We can also implement filter functionality to the Datatable, for that follow a few steps and you will get the desired records into the Datatable.
 
For that, we can create a new component by using the command.
  1. ng g c withfiltering
Open the withfiltering.component.html file and replace the following code snippet.
  1. <mat-card>  
  2.     <div class="alert alert-info">  
  3.         <strong>Angular Material DataTable With Filtering</strong>  
  4.     </div>  
  5.     <div class="example-container mat-elevation-z8">  
  6.         <div class="">  
  7.             <mat-form-field style="width: 98%;">  
  8.                 <input matInput (keyup)="Filter($event.target.value)" placeholder="Filter">  
  9.             </mat-form-field>  
  10.         </div>  
  11.         <mat-table #Table [dataSource]="MyDataSource">  
  12.             <!-- For ID -->  
  13.             <ng-container matColumnDef="id">  
  14.                 <mat-header-cell *matHeaderCellDef> ID </mat-header-cell>  
  15.                 <mat-cell *matCellDef="let post"> {{post.id}} </mat-cell>  
  16.             </ng-container>  
  17.   
  18.             <!-- For Post ID -->  
  19.             <ng-container matColumnDef="postId">  
  20.                 <mat-header-cell *matHeaderCellDef> Post ID </mat-header-cell>  
  21.                 <mat-cell *matCellDef="let post"> {{post.postId}} </mat-cell>  
  22.             </ng-container>  
  23.   
  24.             <!-- For Name -->  
  25.             <ng-container matColumnDef="name">  
  26.                 <mat-header-cell *matHeaderCellDef> Name </mat-header-cell>  
  27.                 <mat-cell *matCellDef="let post"> {{post.name}} </mat-cell>  
  28.             </ng-container>  
  29.   
  30.             <!-- For Email ID -->  
  31.             <ng-container matColumnDef="email">  
  32.                 <mat-header-cell *matHeaderCellDef> Email ID </mat-header-cell>  
  33.                 <mat-cell *matCellDef="let post"> {{post.email}} </mat-cell>  
  34.             </ng-container>  
  35.   
  36.             <!-- For Body -->  
  37.             <ng-container matColumnDef="body">  
  38.                 <mat-header-cell *matHeaderCellDef> Body Text</mat-header-cell>  
  39.                 <mat-cell *matCellDef="let post"> {{post.body}} </mat-cell>  
  40.             </ng-container>  
  41.   
  42.             <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>  
  43.             <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>  
  44.         </mat-table>  
  45.         <!-- To paginate between pages with search -->  
  46.         <mat-paginator #paginator [pageSize]="10" [pageSizeOptions]="[5, 10, 20]">  
  47.         </mat-paginator>  
  48.     </div>  
  49. </mat-card>  
In this HTML file, you can see that I have added textbox which is used to get the value from the user and perform filter operations in the data table.
  1. <mat-form-field style="width: 98%;">  
  2.                <input matInput (keyup)="Filter($event.target.value)" placeholder="Filter">  
  3.            </mat-form-field>  
Whenever a user starts typing to filter the records, at that time a Filter() event will be triggered and get the matchning records.
 
In order to implement evenly, open the withfiltering.component.ts file and paste the following code snippet. 
  1. import { Component, OnInit ,ViewChild} from '@angular/core';  
  2. import { MatTableDataSource,MatPaginator } from '@angular/material';  
  3. import { DataServiceService } from '../service/data-service.service';  
  4. import { MatSort } from '@angular/material';  
  5. import { BehaviorSubject } from 'rxjs/BehaviorSubject';  
  6. import { Observable } from 'rxjs/Observable';  
  7.   
  8. @Component({  
  9.   selector: 'app-withfiltering',  
  10.   templateUrl: './withfiltering.component.html',  
  11.   styleUrls: ['./withfiltering.component.css']  
  12. })  
  13. export class WithfilteringComponent implements OnInit {  
  14.   
  15.   MyDataSource: any;  
  16.   displayedColumns = ['id''postId','name','email','body'];  
  17.   @ViewChild(MatPaginator) paginator: MatPaginator;   
  18.   constructor(public dataService: DataServiceService) { }  
  19.   ngOnInit() {  
  20.     this.RenderDataTable();  
  21.   }  
  22.   
  23.   RenderDataTable() {  
  24.     this.dataService.GetAllComments()  
  25.       .subscribe(  
  26.       res => {  
  27.         this.MyDataSource = new MatTableDataSource();  
  28.         this.MyDataSource.data = res;  
  29.         this.MyDataSource.paginator = this.paginator;  
  30.         console.log(this.MyDataSource.data);  
  31.       },  
  32.       error => {  
  33.         console.log('There was an error while retrieving Comments !!!' + error);  
  34.       });  
  35.   }  

  36.   Filter(searchstring:string)  
  37.   {  
  38.     searchstring = searchstring.trim();   
  39.     searchstring = searchstring.toLowerCase();  
  40.     this.MyDataSource.filter = searchstring;  
  41.   }  
  42. }  
Code explanation
 
In the above component file, we have implemented the filter method in order to filter the records. 
  • filter()
It will be triggered every time the user input value is changed and also is going to populate the data table with the updated records.
 
To populate the data table with the dummy records, I'm using Fake REST API service and getting the records using API URL.
 
https://jsonplaceholder.typicode.com/comments 
 
In the first part of this series, we have created a service file named data-service.ts file, so open the file and add the following method to get the list of comments. 
  1. // To fill the Datatable with Comments [Dummy Data]  
  2.  public GetAllComments() {  
  3.    return this.http.get(this._baseUrl + 'comments')  
  4.      .map((res: Response) => {  
  5.        return res.json();  
  6.      })  
  7.      .catch(this.handleError);  
  8.  }  

So far, we have implemented filter functionality using Angular Material Datatable, now it's time to see how it works.

Angular Material Datatable with Angular
 
This is how we have implemented the filter functionality, isn't it simple? Our next move is to implement the combined example where we are going to include all the functionality like Pagination, Filtering, Sorting, Searching etc.
 
Combined example of Angular Material Datatable with all the functionalities
 
To implement this example, we can create a new separate component by executing the below ng command.
  1. ng g c combined  

Now, open the combined.component.html file and replace it with the following code snippet.

  1. <mat-card>  
  2.     <div class="alert alert-info">  
  3.         <strong>Combined Angular DataTable Demo With All Functionality</strong>  
  4.     </div>  
  5.     <div class="example-container mat-elevation-z8">  
  6.         <!-- For Filtering -->  
  7.         <div class="">  
  8.             <mat-form-field style="width: 98%;">  
  9.                 <input matInput (keyup)="Filter($event.target.value)" placeholder="Filter">  
  10.             </mat-form-field>  
  11.         </div>  
  12.         <mat-table #Table [dataSource]="MyDataSource" matSort>  
  13.   
  14.             <!-- For ID -->  
  15.             <ng-container matColumnDef="id">  
  16.                 <mat-header-cell *matHeaderCellDef mat-sort-header> ID </mat-header-cell>  
  17.                 <mat-cell *matCellDef="let post"> {{post.id}} </mat-cell>  
  18.             </ng-container>  
  19.   
  20.             <!-- For User ID -->  
  21.             <ng-container matColumnDef="userId">  
  22.                 <mat-header-cell *matHeaderCellDef mat-sort-header> User ID </mat-header-cell>  
  23.                 <mat-cell *matCellDef="let post"> {{post.userId}} </mat-cell>  
  24.             </ng-container>  
  25.   
  26.             <!-- For Title -->  
  27.             <ng-container matColumnDef="title">  
  28.                 <mat-header-cell *matHeaderCellDef mat-sort-header> Title </mat-header-cell>  
  29.                 <mat-cell *matCellDef="let post"> {{post.title}} </mat-cell>  
  30.             </ng-container>  
  31.   
  32.             <!-- For Completion Status -->  
  33.             <ng-container matColumnDef="completed">  
  34.                 <mat-header-cell *matHeaderCellDef mat-sort-header> Completion Status</mat-header-cell>  
  35.                 <mat-cell *matCellDef="let post"> {{post.completed}} </mat-cell>  
  36.             </ng-container>  
  37.   
  38.             <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>  
  39.             <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>  
  40.         </mat-table>  
  41.   
  42.         <!-- To paginate between pages with search -->  
  43.         <mat-paginator #paginator [pageSize]="10" [pageSizeOptions]="[5, 10, 20]">  
  44.         </mat-paginator>  
  45.     </div>  
  46. </mat-card>  

This HTML file contains all of the code which is used to implement the datatable with all the functionalities.

Since this is a combined example of what we did previously, I'm not going to explain again about that, it's just like a wrapping up all the example covered in this two-part of series.
 
Now, open combined.component.ts file and replace with the following code snippet.
  1. import { Component, OnInit ,ViewChild} from '@angular/core';  
  2. import { MatTableDataSource,MatPaginator,MatSort } from '@angular/material';  
  3. import { DataServiceService } from '../service/data-service.service';  
  4. import { BehaviorSubject } from 'rxjs/BehaviorSubject';  
  5. import { Observable } from 'rxjs/Observable';  
  6.   
  7. @Component({  
  8.   selector: 'app-combined',  
  9.   templateUrl: './combined.component.html',  
  10.   styleUrls: ['./combined.component.css']  
  11. })  
  12. export class CombinedComponent implements OnInit {  
  13.   
  14.   MyDataSource: any;  
  15.   displayedColumns = ['id''userId','title','completed'];  
  16.   @ViewChild(MatPaginator) paginator: MatPaginator;  
  17.   @ViewChild(MatSort) sort: MatSort;  
  18.   
  19.   constructor(public dataService: DataServiceService) { }  
  20.   
  21.   ngOnInit() {  
  22.     this.RenderDataTable();  
  23.   }  
  24.   
  25.   RenderDataTable() {  
  26.     this.dataService.GetAllTodos()  
  27.       .subscribe(  
  28.       res => {  
  29.         this.MyDataSource = new MatTableDataSource();  
  30.         this.MyDataSource.data = res;  
  31.         this.MyDataSource.sort = this.sort;  
  32.         this.MyDataSource.paginator = this.paginator;  
  33.         console.log(this.MyDataSource.data);  
  34.       },  
  35.       error => {  
  36.         console.log('There was an error while retrieving Todos !!!' + error);  
  37.       });  
  38.   }  
  39.   
  40.   Filter(searchstring:string)  
  41.   {  
  42.     searchstring = searchstring.trim();   
  43.     searchstring = searchstring.toLowerCase();  
  44.     this.MyDataSource.filter = searchstring;  
  45.   }  
  46.   
  47. }  

It contains the all necessary code used for a different operation like Pagination, Filtering, Sorting etc.

For populating data table with the records, using the following Rest API.
 
https://jsonplaceholder.typicode.com/todos
 
To populate the data, we are going to call a method which is used to get the list of todos and then we will populate all those records into the data table.
 
For that open data-service.service.ts file and add additional method.
  1. // To fill the Datatable with Todos [Dummy Data]  
  2. public GetAllTodos() {  
  3.   return this.http.get(this._baseUrl + 'todos')  
  4.     .map((res: Response) => {  
  5.       return res.json();  
  6.     })  
  7.     .catch(this.handleError);  
  8. }  

We are done with our example, now let's quickly run our example and see the complete and full fledged working Angular Material Datatable with different functionalities.

Angular Material Datatable with Angular 
 
As you can see in the above figure, all the basic features were implemented.
 
Conclusion
 
In this part of the article, we have implemented filtering which contains all of the possible functionalities like Pagination, Filtering, Sorting etc.
 
Angular Material Datatable is a very effective and handy tool and it's pretty easy to implement such kind of different functionalities and can also provide different styles as per the requirement. I would recommend you to download the source code and implement it on your own.
 
Thanks for reading.