Reset this.dataSource.filterPredicate in Angular

Viewed 1163

I am using a filter and a select on my mat-table, In order to filter using the select I am using filtered predicate on the concerned field.

public applyFilter(filterValue: string) {
    this.dataSource.filterPredicate = (data: SP, filter: string) => {
        return data.tag === filter;
    };
    this.dataSource.filter = filterValue;
}

But I also have a standard filter like this for filtering using input field:-

public filter(filterValue: string): void {
    filterValue = filterValue.trim();
    filterValue = filterValue.toLowerCase();
    this.dataSource.filter = filterValue;
}

How do I reset the original filterPredicate so that the second filter becomes operational?

2 Answers

Declare a component level variable defaultFilterPredicate and set it on ngOnInit

defaultFilterPredicate?: (data: any, filter: string) => boolean;

ngOnInit() {
  this.defaultFilterPredicate = this.dataSource.filterPredicate;
}

Then when you need to reset, just set it back to what it was when the component first loaded, ie the default.

this.dataSource.filterPredicate = this.defaultFilterPredicate;

This is just an very ugly patch, but I had the same problem and solved it by looking up the way the original filter functioned in material-table.umd.js and copying that. I know there must be a better way, I also expected that setting back filterPredicate to null should work but it does not. Not the best answer probably, but this works for me:

    public filter(filterValue: string) : void {

    this.dataSource.filterPredicate = 
        function (data, filter) {
            var dataStr = Object.keys(data).reduce(function (currentTerm, key) {
                return currentTerm + data[key] + '◬';
            }, '').toLowerCase();
            var transformedFilter = filter.trim().toLowerCase();
            return dataStr.indexOf(transformedFilter) != -1;
        };

    filterValue = filterValue.trim(); 
    filterValue = filterValue.toLowerCase(); 
    this.dataSource.filter = filterValue;
}
Related