Angular mat-table filter
Filtering data in Angular mat-table by specific columns.
I would like to share with you a solution to the problem of filtering data in Angular mat-table. It will be a question of filtering not the entire table, but the specific columns of this table.
All source and demo you can find on GitHub or Stackblitz.
Let’s start
For example, take a search for routes between two stations and a date.
In my case, these are three columns are filtered:
DEP. Date | DEP. Station | ARR. Station
I don’t see any sense in showing how to create a mat-table, there are no differences from what you find on the official Angular Material website. Let’s go straight to the filter.
How filter work?
Every time when you set the dataSource.filter — Angular passes through all objects (rows) that are currently located in dataSource: MatTableDataSource<> and call filterPredicate().
filterPredicate: ((data: T, filter: string) => boolean);
FilterPredicate checks if a data object matches the data source’s filter string. By default, each data object is converted to a string of its properties and returns true if the filter has at least one occurrence in that string.
That what we are looking for. All what we need it override filterPredicate() method.
Filter
First, consider the method of applying a filter to a table. It is slightly different from the standard.
Here we get the values from our fields and form a string like ‘first_value$second_value$third_value’ and pass this string to the table filter.
FilterPredicate
This is where our overridden filterPredicate comes in.
More details
Since we passed a string formed of three queries to filterPredicate, for a start we need to split it.
In our case, we select data from row by specific cells.
Now we can easily check the cells according to the desired values.
Form an array like [boolean, boolean, boolean] and return true if all values in the array are true, or false if at least one of them is false.
That’s all, the filter is ready.
Thanks for reading, all source and demo you can find on GitHub or Stackblitz.