Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do filter in angular material data table for specific column

i am trying angular material data table.

As we know filtering happened for each row by default.

If i want to filter column specific, then what should i do?

Should i have to write method for getting all records, then iterate over it and compare specific column?

component.ts


ngOnInit() {
    this.service.getUser().subscribe( results => {
        if(!results){

          return;
        }
        console.log(results);
        this.dataSource = new MatTableDataSource(results);
        this.dataSource.sort = this.sort;
    })


onSearchClear(){
    this.searchKey="";
    this.applyFilter();
  }

  applyFilter(){
    this.dataSource.filter = this.searchKey.trim().toLowerCase();
  }

component.html


<mat-form-field class="search-form-field">
      <input matInput [(ngModel)]="searchKey" placeholder="search by userName" (keyup)="applyFilter()">
    </mat-form-field>
like image 310
mohan Avatar asked Dec 14 '25 08:12

mohan


1 Answers

you should use filterPredicate property of MatTableDataSource

after you initialize this.dataSource, define a custom filterPredicate function as follows;

this.dataSource = new MatTableDataSource(results);
this.dataSource.sort = this.sort;
this.dataSource.filterPredicate = function(data: any, filterValue: string) {
  return data.specificColumn /** replace this with the column name you want to filter */
    .trim()
    .toLocaleLowerCase().indexOf(filterValue.trim().toLocaleLowerCase()) >= 0;
};
like image 133
ysf Avatar answered Dec 15 '25 22:12

ysf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!