加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

角度 – mat-table中的自定义过滤器

发布时间:2020-12-17 08:34:12 所属栏目:安全 来源:网络整理
导读:我正在使用mat-table.它有一个过滤器,可以正常使用doc示例: 从https://material.angular.io/components/table/overview起,原始代码为: div class="example-header" mat-form-field input matInput (keyup)="applyFilter($event.target.value)" placeholder
我正在使用mat-table.它有一个过滤器,可以正常使用doc示例:

从https://material.angular.io/components/table/overview起,原始代码为:

<div class="example-header">
       <mat-form-field>
         <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter">
       </mat-form-field>
   </div>

   <mat-table #table [dataSource]="dataSource">
      <!-- the rest of the code -->
   </mat-table>
export class TableFilteringExample {
     displayedColumns = ['position','name','weight','symbol'];
     dataSource = new MatTableDataSource(ELEMENT_DATA);

     applyFilter(filterValue: string) {
       filterValue = filterValue.trim(); // Remove whitespace
       filterValue = filterValue.toLowerCase(); // MatTableDataSource defaults to lowercase matches
       this.dataSource.filter = filterValue;
     }
    }
    const ELEMENT_DATA: Element[] = [
     {position: 1,name: 'Hydrogen',weight: 1.0079,symbol: 'H'},{position: 2,name: 'Helium',weight: 4.0026,symbol: 'He'},{position: 3,name: 'Lithium',weight: 6.941,symbol: 'Li'},{position: 4,name: 'Beryllium',weight: 9.0122,symbol: 'Be'},{position: 5,name: 'Boron',weight: 10.811,symbol: 'B'}
    ];

有了这个实现,当过滤时,它会过滤任何列.

现在我正在尝试更改过滤器,因为我想要的是“name”列的过滤器,所以我试图重写过滤器并分配给filterData.

applyFilter(filterValue: string) {
        filterValue = filterValue.trim(); // Remove whitespace
        filterValue = filterValue.toLowerCase(); // MatTableDataSource defaults to lowercase matches
       this.dataSource.filteredData = this.filterByEmail(filterValue); 
        console.log(this.dataSource.filteredData); //value is what I want.
    }

    filterByName(filter: string): any {
      const dataFiltered = this.data.filter(function(item){
         return item.name.indexOf(filter) > -1
       })
        return dataFiltered;
    }

在控制台中,我可以看到this.dataSource.filteredData具有我想要打印的数据,但表没有重新加载.

我错过了什么?

我找到了解决方案 here.

有必要重写filterPredicate,并且像往常一样使用它,filterPredicate需要在过滤器传递时返回true,而当它没有时返回false

export interface Element {
 name: string;
 position: number;
 weight: number;
 symbol: string;
}


dataSource = new MatTableDataSource(ELEMENT_DATA);
/* configure filter */
this.dataSource.filterPredicate = 
  (data: Element,filter: string) => data.name.indexOf(filter) != -1;


applyFilter(filterValue: string) {
   filterValue = filterValue.trim(); // Remove whitespace
   filterValue = filterValue.toLowerCase(); // MatTableDataSource defaults to lowercase matches
   this.dataSource.filter = filterValue;
 }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读