Angular Material Table filterPredicate

Angular Material Table filterPredicate

我正在尝试按特定对象键过滤一组数据 例如:我有一组技能,我想在 2 级查看所有技能。

我已经通读了文档,this GitHub example, and this other question但是我找不到一个实际的例子来说明如何使用用户输入来按对象键进行过滤。到目前为止,当用户点击技能级别时没有任何反应。

现在我的 HTML 看起来像:

<mat-button-toggle-group #group="matButtonToggleGroup"
    class="margin-1" (change)=toggleSkillLevel(group.value)>

  <mat-button-toggle value="0">
    0
  </mat-button-toggle>

  <mat-button-toggle value="1">
    1
  </mat-button-toggle>

  <mat-button-toggle value="2">
    2
  </mat-button-toggle>

  <mat-button-toggle value="all">
    ALL
  </mat-button-toggle>

</mat-button-toggle-group>

{{ dataSource.filteredData }}

我的 TS 看起来像:

 import { Skill, SKILL_DATA } from '../data/skills-details';

...
...

  toggleSkillLevel(level){
    console.log('Only show level ' + level + ' skills...');
    this.dataSource.filterPredicate =
            (data: Skill, filter: string) => data.level == level;
  }

通过设置 filterPredicate,您只需定义在给定过滤值时应如何将过滤值应用于您的数据。它只是过滤器函数的定义,您实际上并没有用它来应用过滤器。 因此,您只需要定义一次,例如可以在 ngOnInit.

中定义
ngOnInit() {
  this.dataSource.filterPredicate =
      (data: Skill, filter: string) => !filter || data.level == filter;
}

然后要应用具有实际值的过滤器,您需要设置 dataSource.filter,例如:

toggleSkillLevel(level) {
  this.dataSource.filter = level;
}

只想对 Kim Kern 的回答进行补充。

如果您应用此方法并开始收到如下错误:

TypeError: Cannot read property 'filter' of null
at MatTableDataSource._filterData (http://localhost.satin.lo:7000/vendor.js:88312:18)
at MapSubscriber.project (http://localhost.satin.lo:7000/vendor.js:88291:89)
at MapSubscriber._next (http://localhost.satin.lo:7000/vendor.js:141164:35)
at MapSubscriber.next (http://localhost.satin.lo:7000/vendor.js:137246:18)
at CombineLatestSubscriber.notifyNext (http://localhost.satin.lo:7000/vendor.js:137998:34)
at InnerSubscriber._next (http://localhost.satin.lo:7000/vendor.js:136528:21)
at InnerSubscriber.next (http://localhost.satin.lo:7000/vendor.js:137246:18)
at BehaviorSubject.next (http://localhost.satin.lo:7000/vendor.js:137030:25)
at BehaviorSubject.next (http://localhost.satin.lo:7000/vendor.js:136499:15)
at MatTableDataSource.set filter [as filter] (http://localhost.satin.lo:7000/vendor.js:88238:22)

此错误是由于您的 dataSource.data 在您调用 this.dataSource.filter = xyz;

的时间点处于 null 的结果

我有类似这样的设置来自父组件的数据源 ajax 调用:

@Input() set items(data: IItem[]) {
     this.dataSource.data = data;
}

Observable 的默认值是 null。所以我通过简单的空检查解决了这个问题:

@Input() set items(data: IItem[]) {
    if(data){
        this.dataSource.data = data;
    }
}