我有一个Angular MatTableDataSource对象,该对象具有许多顶级属性和一个嵌套数组属性,该属性包含与该行相关的ID列表。
MatTableDataSource数组中的每个条目看起来如下:
IMSI: 505230000000006,
isActive: "Yes",
APNList: [1,2,3,4,5]
我还有一个多垫选择元素,我可以从中选择一个或多个与APNList嵌套数组中的条目相关的ID。
我需要在multiselect的selectionChange事件上创建一个过滤器,通过将mat-select返回的数组与每个条目中的嵌套数组相匹配来过滤MatTableDataSource。
因此,例如,在select中选择1和2将过滤MatTableDataSource,使其APNList数组中只有1和/或2的条目。
我觉得filterPredicate和ES6-some((的组合会完成任务,但我还没有完全了解如何实现它
如有任何帮助,我们将不胜感激!
您有两个选项,我将从创建随机数据源开始。
type entry = {
IMSI: number;
isActive: string;
APNList: number[];
};
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.scss'],
})
export class TestComponent implements OnInit {
dataSource: MatTableDataSource<entry> = new MatTableDataSource([
{ IMSI: 505230000000006, isActive: 'Yes', APNList: [1, 2, 3, 4, 5] },
{ IMSI: 505230000000007, isActive: 'Yes', APNList: [6, 7, 8, 9, 10] },
{ IMSI: 505230000000008, isActive: 'Yes', APNList: [1, 2, 3, 4, 5] },
]);
...
为了简单起见,我将对1和2的检查进行硬编码,显然您的函数将具有允许不同搜索的参数。
选项1:使用filter()
直接过滤数据阵列
option1() {
const data: entry[] = this.dataSource.data;
const filteredData: entry[] = data.filter(
(entry) => entry.APNList.includes(1) || entry.APNList.includes(2)
);
console.log(filteredData);
}
filter()
有一个函数作为参数,该函数需要返回true
才能使元素通过过滤器。
选项2:使用MatTableDataSource
类间接过滤数据数组
option2() {
this.dataSource.filterPredicate = (entry: entry, filter: string) =>
entry.APNList.includes(1) || entry.APNList.includes(2);
//Data is only filtered after updating the filter string
this.dataSource.filter = 'Some filter string';
console.log('Option2: ', this.dataSource.filteredData);
}
我们可以提供一个自定义的过滤器函数作为filterPredicate
属性,与filter()
相同。然而,该函数具有第二个string
参数,该参数对应于MatTableDataSource
类的filter
属性。您应该使用此筛选字符串来筛选您的数据。
过滤后的数据显示在类的filteredData
属性中。请记住,filteredData
仅在filter
属性更改时更新。此外,如果filter
属性为空,则filteredData
将包含所有数据,而与函数无关。文档中的更多信息:https://material.angular.io/components/table/api#MatTableDataSource
堆叠闪电战:https://stackblitz.com/edit/angular-ivy-zamkgj?file=src/app/test/test.component.ts