在官方的 Angular stackblitz 示例中,dataSource 有一个 1 级深度的对象数组,通过 console.log(this.dataSource.filteredData) 可以明显看出:
但是,您的 dataSource 在 Match 对象中嵌套了另一层对象两次(即 MatchDetails 和 MoveInVideo 对象嵌套在 Match 对象中):
因此,提供的过滤器功能对您不起作用,因为它仅根据过滤器值检查第一级对象(匹配)。事实上,它通过返回[] 可以正常工作,因为您的 Match 对象中没有任何值与过滤器值匹配。如果您搜索“originalFilterPosterId”,它将返回所有对象,因为所有匹配对象都包含此值。
您可以通过在调用applyFilter() 事件处理程序之前在 ngOnInit() 中设置通用filterPredicate 来解决此问题。这个通用函数将能够过滤嵌套对象。所有感谢 @Sagar Kharche 和 @mighty_mite Stackover answer source。
ngOnInit(){
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
//set a new filterPredicate function
this.dataSource.filterPredicate = (data, filter: string) => {
const accumulator = (currentTerm, key) => {
return this.nestedFilterCheck(currentTerm, data, key);
};
const dataStr = Object.keys(data).reduce(accumulator, '').toLowerCase();
// Transform the filter by converting it to lowercase and removing whitespace.
const transformedFilter = filter.trim().toLowerCase();
return dataStr.indexOf(transformedFilter) !== -1;
}
}
//also add this nestedFilterCheck class function
nestedFilterCheck(search, data, key) {
if (typeof data[key] === 'object') {
for (const k in data[key]) {
if (data[key][k] !== null) {
search = this.nestedFilterCheck(search, data[key], k);
}
}
} else {
search += data[key];
}
return search;
}
您无需更改 applyFilter() 函数中的任何内容。
Forked Stackblitz Example ⚡