Search code examples
angularangular-materialangular-material-table

Reset this.dataSource.filterPredicate in Angular


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?


Solution

  • 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;