Javascript Angular Material Table filterPredicate
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48470046/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular Material Table filterPredicate
提问by av0000
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 questionbut I can't find an actual example of how user input can be used to filter by an object key. So far nothing happens when a user clicks on a skill level.
我已经通读了文档、这个 github 示例和另一个问题,但我找不到如何使用用户输入按对象键进行过滤的实际示例。到目前为止,当用户点击某个技能级别时,没有任何反应。
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 Kim Kern
By setting the filterPredicate, you only define how a filter value should be applied on your data when a filter value is given. 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.
通过设置filterPredicate,您只能定义在给定过滤器值时应如何将过滤器值应用于您的数据。这只是过滤器函数的定义,您实际上并没有将过滤器应用于它。因此,您只需要定义一次,这可能发生在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;
}

