[Table] - Add example with multiple filtering columns
Bug, feature request, or proposal:
Proposal.
What is the expected behavior?
It would be good to see an example showing multiple filters (in this case inputs/selects) to filter rows/cells in md-table.
You can see this as an example.
What is the current behavior?
Currently the filter example just shows how to filter multiple columns by a single input.
@patrickschlaepfer I think i have no idea of your exception! 🤣
@irowbin I also get cannot read property of 'templateRef' of undefined. From what I can tell the html bit <filter-template [openFilter]="true" ... needs to have some sort of templateRef passed to it
didn't try but i think typo is here <filter-template [openFilter]="true" *ngIf="templateFor === 'col1">
missing single quote in col1
@patrickschlaepfer @erickyi2006 Maybe there is some typo i guess. 😆
<filter-template [openFilter]="true" *ngIf=" templateFor === 'col1' "></filter-template>
I used a different approach; since MatTableDataSource.filter only accepts a string as an argument, I created a custom filterPredicate where each input passes an object that has been stringified.
With two form controls like this in the template:
<mat-form-field>
<input matInput [formControl]="idFilter" placeholder="id">
</mat-form-field>
<mat-form-field>
<input matInput [formControl]="nameFilter" placeholder="name">
</mat-form-field>
I subscribed to value changes in the ts:
private idFilter = new FormControl();
private nameFilter = new FormControl();
private filterValues = {id: '', name: ''}
this.idFilter.valueChanges
.subscribe(value => {
this.filterValues['id'] = value;
this.dataSource.filter = JSON.stringify(this.filterValues)
})
this.nameFilter.valueChanges
.subscribe(value => {
this.filterValues['name'] = value
this.dataSource.filter = JSON.stringify(this.filterValues)
})
// custom filterPredicate function:
this.dataSource.filterPredicate = this.createFilter();
createFilter() {
let filterFunction = function(data, filter) : boolean {
let searchTerms = JSON.parse(filter)
return data.id.toString().indexOf(searchTerms.id) != -1
&& data.name.indexOf(searchTerms.name) != -1
}
return filterFunction
}
@alexisdoualle it's work for me. Tks <3
@alexisdoualle Where are the values for data and filter in function createFilter( ), do they get auto assigned or do we have to pass some value to them ?
No proper documention for using filterPredicate in the Angular Material, so having a hard time understanding how it actually works
@drop039beats Yes they are auto assigned, you don't have to worry about them. By creating your own predicate function, you're overriding the default filter function, which only checks for the presence of string "filter" in the available data (MatTableDataSource). With a custom function you can specify which field you want to check (as in data.id), and with my workaround you can assign each input to every field in the table.
You can create a MatTableDataSource object simply like this:
this.dataSource = new MatTableDataSource()
this.dataSource.filterPredicate = this.createFilter();
this.dataSource.data = yourData
@alexisdoualle Thanks a lot it worked like charm, we need to set filterPredicate before we set the dataSource.filter that is why it was not working for me. Better to put it in onNgInit( )
I had to make the filterPredicate dynamic based on the number of columns to be filtered
public createFilter(): (data: any, filter: any) => boolean {
const filterFunction = function(data, filter): boolean {
const searchData = JSON.parse(filter);
let status = false;
for (const key in searchData) {
if (data[key].indexOf(searchData[key]) !== -1) {
status = true;
} else {
status = false;
break;
}
}
return status;
};
return filterFunction;
}
@alexisdoualle With your implementation are you able to search two terms within the same column? I did something similar with a custom predicate but I wasn't able to do something like search for 'John' and 'Bob' in the name filter at the same time.
@srukali Sure, if you want to have only one filter for names and be able to search multiple names separated by, say, a white space, you could do something like this:
createFilter() {
let filterFunction = function(data: any, filter: string) : boolean {
let searchTerms = JSON.parse(filter)
let idSearch = data.id.toString().indexOf(searchTerms.id) != -1
let nameSearch = () => {
let found = false;
searchTerms.name.trim().toLowerCase().split(' ').forEach(word => {
if (data.name.toLowerCase().indexOf(word) != -1) {found = true}
});
return found
}
return idSearch && nameSearch()
}
return filterFunction
}
@alexisdoualle, I use your createFilter function. If I have two arguments (like name and id), all works fine. But if I return third value, data is not displayed
@irowbin any chance we can get a stackblitz for the gif you shared?
stackblitz would be great!
Building on-top of what @alexisdoualle has given for a per-column filtering solution I would like to add in how I managed to fit my filter inputs inside of my table column headers instead of else-where on the page. Also not have them trigger column sorting when they are focused for input.
I'd like to preface with saying this is just a proof of concept and small snippet, I hope it helps though!
<ng-container *ngFor="let column of displayedColumns" matColumnDef="{{column}}">
<mat-header-cell *matHeaderCellDef>
<span mat-sort-header>{{column | uppercase}}</span>
<input class="filter-input" matInput (keyup)="applyFilter(column, $event.target.value)" placeholder="Filter {{column}}" />
</mat-header-cell>
<mat-cell *matCellDef="let row"> {{row[column]}}</mat-cell>
</ng-container>
If you are NOT using mat-sort functionality then the trick is simple, just include your filter input inside of the mat-header-cell. If you are using mat-sort functionality then you will need to instead put your column heading text inside of a span and give that span the mat-sort-header class instead of the mat-header-cell.
Sample result:

Is it possible to have it both ways? I mean filtering on the full table and per column? I don't see how to do it after modifying the filterPredicate. Anyone?
@alexisdoualle 's solution worked for me.But I still can't figure out a way to retain the default filter once filterPredicate is overriden.
StackBlitz
I'm for a way to filter on top of whatever data the column filters return.
Is this even possible after overriding filterPredicate
@kal93 @jordanA29 https://stackblitz.com/edit/angular-hbakxo-xctfqy?file=app/table-filtering-example.ts
This lets you have individual filters for each column and a top-level filter for all columns (which you can test with the value '999')
The trick was adding a property to the stringified object (.topFilter), which when set to true (by the top-level form control) will make the custom predicate function use the OR operator, so that every field is parsed, like in the default predicate.
customFilterPredicate() {
const myFilterPredicate = function(data:PeriodicElement, filter:string) :boolean {
let searchString = JSON.parse(filter);
let nameFound = data.name.toString().trim().toLowerCase().indexOf(searchString.name.toLowerCase()) !== -1
let positionFound = data.position.toString().trim().indexOf(searchString.position) !== -1
if (searchString.topFilter) {
return nameFound || positionFound
} else {
return nameFound && positionFound
}
}
return myFilterPredicate;
}
Of course, if you want all columns to be parsed (like 'weight' and 'symbol'), you need to add them to the code, either explicitly, or by looping through the 'data' parameter's properties.
data.name.toString().trim().toLowerCase().indexOf(searchString.name.toLowerCase()) !== -1
Hey Do you have any example how we can achieve same functionality of filter on each column using dynamic data? Thank you
@kal93 @jordanA29 https://stackblitz.com/edit/angular-hbakxo-xctfqy?file=app/table-filtering-example.ts
This lets you have individual filters for each column and a top-level filter for all columns (which you can test with the value '999')
The trick was adding a property to the stringified object (.topFilter), which when set to true (by the top-level form control) will make the custom predicate function use the OR operator, so that every field is parsed, like in the default predicate.
customFilterPredicate() { const myFilterPredicate = function(data:PeriodicElement, filter:string) :boolean { let searchString = JSON.parse(filter); let nameFound = data.name.toString().trim().toLowerCase().indexOf(searchString.name.toLowerCase()) !== -1 let positionFound = data.position.toString().trim().indexOf(searchString.position) !== -1 if (searchString.topFilter) { return nameFound || positionFound } else { return nameFound && positionFound } } return myFilterPredicate; }Of course, if you want all columns to be parsed (like 'weight' and 'symbol'), you need to add them to the code, either explicitly, or by looping through the 'data' parameter's properties.
Hey Do you have any example how we can achieve same functionality of filter on each column using dynamic data? Thank you