mohan
mohan

Reputation: 457

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>

Upvotes: 2

Views: 23426

Answers (2)

Code Spy
Code Spy

Reputation: 9954

Check this tutorial and working demo

enter image description here

Upvotes: 8

ysf
ysf

Reputation: 4844

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

Upvotes: 10

Related Questions