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

心已入冬 提交于 2021-01-01 17:47:21

问题


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>

回答1:


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



回答2:


Check this tutorial and working demo



来源:https://stackoverflow.com/questions/56620674/how-to-do-filter-in-angular-material-data-table-for-specific-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!