Angular6:筛选与属性匹配的列表元素



我想通过仅显示具有特定groupId属性的项目来过滤角度表的数据源

组件.html

<mat-table [dataSource]="groupSource |  filter : currentGroupId"></mat-table>

filter.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filter'
})
// return items of a group
export class FilterPipe implements PipeTransform {
transform(group: any[], currentGroupId: number): any[] { 
return group.filter( item=> item.groupId = currentGroupId);
}
}

但是,我收到此错误:

错误

类型错误:group.filter 不是
FilterPipe.push 中的函数。/src/app/filter.pipe.ts.FilterPipe.transform (filter.pipe.ts:9(at checkAndUpdatePureExpressionInline (core.js:9949(at checkAndUpdateNodeInline (core.js:10518(at checkAndUpdateNode (core.js:10476(at



debugCheckAndUpdateNode (core.js:
11109(at debugCheckDirectivesFn (core.js:11069(at Object.eval [as updateDirectives] (
BasketComponent.html:144(at
Object.debugUpdateDirectives [as updateDirectives] (core.js:11061(
at checkAndUpdateView (core.js:10458(
at callViewAction (core.js:10699(

我做错了什么?

问题在于相等性检查。它应该是

return group.filter( item=> item.groupId === currentGroupId);

当您提供的数据源可能是不是数组的 MatTableDataSource 实例时,您正在尝试对数组使用 filter 方法。事实上,MatTableDataSource有一个过滤器属性,它应该是一个字符串。

但是,您需要使用 MatTableDataSource 的 filterPredicate 函数。

阅读文档,了解筛选材质数据源的正确方法。

最新更新