简体   繁体   English

Angular Material Table filterPredicate

[英]Angular Material Table filterPredicate

I'm trying to filter a set of data by a specific object key Ex: I have a set of skills, I want to see all of the skills at level 2. 我试图通过特定的对象密钥过滤一组数据例如:我有一套技能,我希望看到2级的所有技能。

I have read through the docs, this github example , and this other question but I can't find an actual example of how user input can be used to filter by an object key. 我已经阅读了文档, 这个github示例 ,以及另一个问题,但我找不到用户输入如何用于按对象键过滤的实际示例。 So far nothing happens when a user clicks on a skill level. 到目前为止,当用户点击技能级别时没有任何反应。

Any pointers would be appreciated. 任何指针将不胜感激。

Right now my html looks like: 现在我的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 }}

and my TS looks like: 我的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;
  }

By setting the filterPredicate , you only define how a filter value should be applied on your data when a filter value is given. 通过设置filterPredicate ,您只需定义在给定过滤器值时应如何对数据应用过滤器值。 It's only the definition of the filter function, you do not actually apply the filter with it. 它只是过滤器功能的定义,实际上并没有应用过滤器。 Hence, you only need to define this once, which could for example happen in the ngOnInit . 因此,您只需要定义一次,例如可以在ngOnInit中进行ngOnInit

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

To then apply your filter with an actual value, you need to set dataSource.filter , for example: 要使用实际值应用过滤器,您需要设置dataSource.filter ,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM