Angular Material Table filterPredicate Angular Material Table filterPredicate javascript javascript

Angular Material Table filterPredicate


By setting the filterPredicate, you only define how a filter value should be applied on your data when a filter value is given. It's only the definition of the filter function, you do not actually apply the filter with it.Hence, you only need to define this once, which could for example happen in the ngOnInit.

ngOnInit() {  this.dataSource.filterPredicate =      (data: Skill, filter: string) => !filter || data.level == filter;}

To then apply your filter with an actual value, you need to set dataSource.filter, for example:

toggleSkillLevel(level) {  this.dataSource.filter = level;}


Just wanted to add an addition to Kim Kern's answer.

If you apply this method and start getting an error like this:

TypeError: Cannot read property 'filter' of nullat MatTableDataSource._filterData (http://localhost.satin.lo:7000/vendor.js:88312:18)at MapSubscriber.project (http://localhost.satin.lo:7000/vendor.js:88291:89)at MapSubscriber._next (http://localhost.satin.lo:7000/vendor.js:141164:35)at MapSubscriber.next (http://localhost.satin.lo:7000/vendor.js:137246:18)at CombineLatestSubscriber.notifyNext (http://localhost.satin.lo:7000/vendor.js:137998:34)at InnerSubscriber._next (http://localhost.satin.lo:7000/vendor.js:136528:21)at InnerSubscriber.next (http://localhost.satin.lo:7000/vendor.js:137246:18)at BehaviorSubject.next (http://localhost.satin.lo:7000/vendor.js:137030:25)at BehaviorSubject.next (http://localhost.satin.lo:7000/vendor.js:136499:15)at MatTableDataSource.set filter [as filter] (http://localhost.satin.lo:7000/vendor.js:88238:22)

This error is the result of your dataSource.data being null at the point in time that you call this.dataSource.filter = xyz;

I had something like this setting my dataSource from a parent components ajax call:

@Input() set items(data: IItem[]) {     this.dataSource.data = data;}

The default value from the observable was null. So I resolved this issue with a simple null check:

@Input() set items(data: IItem[]) {    if(data){        this.dataSource.data = data;    }}