Search code examples
angular7angular-material2

Mat table filer on exact match


How can I filter on an exact match?

If I filter on 25915b8d-8b7c-41fe-b015-9b2e0a7d194b then both

25915b8d-8b7c-41fe-b015-9b2e0a7d194b 1225915b8d-8b7c-41fe-b015-9b2e0a7d194b

are returned. I want exact match and not contains.

  applyFilter(filterValue: string) {
filterValue = filterValue.trim(); 
filterValue = filterValue.toLowerCase();
this.dataSource.filter = filterValue;

}


Solution

  • you should use filterPredicate property of MatTableDataSource

    https://material.angular.io/components/table/api#MatTableDataSource

    after you initialize this.dataSource (i am assuming that "25915b8d-8b7c-41fe-b015-9b2e0a7d194b" is a field named "uuid" on T);

    this.dataSource.filterPredicate = function(data: T, filterValue: string) {
      return data.uuid
        .trim()
        .toLocaleLowerCase() === filterValue;
    };
    

    you should replace T with whatever type you are using on your MatTableDataSource<T>

    also keep in mind that;

    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.

    which means, by using above filterPredicate you will be filtering the datasource based on only one field of your data. if your use case requires to filter multiple fields, then you should adopt your filterPredicate function accordingly.