Angular Material Data table Filtering

Features like filtering, sorting and pagination have been made really simple in angular material let's take a look at filtering in this article. Filtering can be achieved in three simple steps the first step is create a data source as an instance of the MatTableDataSource class, so let's being by importing MatTableDataSource from @angular/material next we create a dataSource property as an instance of this imported class and then we pass in ELEMENT_DATA as an argument.

import { MatTableDataSource } from "@angular/material";

export class AppComponent implements OnInit {

  displayedColumns: string[] = ["position", "name", "symbol", "weight"];
  dataSource = new MatTableDataSource(ELEMENT_DATA);

}

So that was our first step creating the dataSource as an instance of the MatTableDataSource class.

Second step is to create an input field where the user can enter the filter text let's add that code in the HTML.

<mat-form-field>
  <input matInput placeholder="Filter" />
</mat-form-field>

Every time the user enters some text we need to filter the data table for that we listen to keyup event and we're gonna call a method called applyFilter() and to this method we pass in the filter text which is accessed using $event.target.value.

<mat-form-field>
  <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter" />
</mat-form-field>

The final step is to define this applyFilter() method which actually filters the data source so back in the component class and all we have to is to assign the filter text value to the filter property of the dataSource.

  applyFilter(filterValue: string) {
    this.dataSource.filter = filterValue;
  }

This kind of seems like magic but let me tell you how it works, remember the MatTableDataSource class that we've imported well that class has a property called filter, when you want to filter out the data all you have to do is assign a string to that property when you assign the filter value the dataSource will reduce each row to serialized form and will filter out the row is it does not contain that filtered value, in simple terms does the data row contain the filter value if yes only then display the row.

So if you take a look at the browser you can see that we have a filter input I type 'H' and you can see it filters the elements continue typing 'He' and it filters further1. angular material data table filtering

I can also filter on numeric values type '6' and you can see it filters out the rows that don't contain the number 6.

So three basic steps for filtering:

  1. Creating the dataSource as an instance of MatTableDataSource.
  2. Creating the input filter.
  3. On keyup of that input element assign the filter value to the filter property of the dataSource.