Angular mat表排序不使用对象路径键
我想在mat table中使用的数据不是平坦的,而是不同对象的层。我可以很好地显示数据,但排序不起作用。下面是一个使用元素数据的示例,其中字段位于“foo”对象内的一层。我怎样才能使分拣工作正常 根据“检查api”选项卡,搜索排序自定义项 允许通过重写sortingDataAccessor进行排序自定义,这 定义如何访问数据属性。还允许使用过滤器 通过重写FilterAccessor进行自定义,它定义了如何 将数据转换为字符串以进行筛选器匹配 这就是您需要的,您需要添加类型为的sortData函数 排序数据:数据:T[],排序:MatSort=>T[] 这里有一个例子Angular mat表排序不使用对象路径键,angular,sorting,mat-table,Angular,Sorting,Mat Table,我想在mat table中使用的数据不是平坦的,而是不同对象的层。我可以很好地显示数据,但排序不起作用。下面是一个使用元素数据的示例,其中字段位于“foo”对象内的一层。我怎样才能使分拣工作正常 根据“检查api”选项卡,搜索排序自定义项 允许通过重写sortingDataAccessor进行排序自定义,这 定义如何访问数据属性。还允许使用过滤器 通过重写FilterAccessor进行自定义,它定义了如何 将数据转换为字符串以进行筛选器匹配 这就是您需要的,您需要添加类型为的sortData函
@ViewChild(MatSort, {static: true}) sort: MatSort;
ngOnInit() {
this.dataSource.sort = this.sort;
this.dataSource.sortData = this.sortData;
}
sortData(data: PeriodicElement[],sort: MatSort): PeriodicElement[] {
if (!sort.active || sort.direction === '') {
return data;
}
return data.sort((a, b) => {
const isAsc = sort.direction === 'asc';
switch (sort.active) {
// Add other cases (columns)
// if you are wondering where is this 'position' coming from, check the html tag for the th below
case 'position': return isAsc ?
(a.foo.position - b.foo.position > 1 ? 1 : -1) :
(a.foo.position - b.foo.position > 1 ? -1 : 1);
default: return 0;
}
});
}}
HTML
<table mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8">
<ng-container matColumnDef="foo.position">
<th mat-header-cell *matHeaderCellDef mat-sort-header> No. </th>
<td mat-cell *matCellDef="let element"> {{element.foo.position}} </td>
</ng-container>
...
</table>
@ViewChild(MatSort, {static: true}) sort: MatSort;
ngOnInit() {
this.dataSource.sort = this.sort;
this.dataSource.sortData = this.sortData;
}
sortData(data: PeriodicElement[],sort: MatSort): PeriodicElement[] {
if (!sort.active || sort.direction === '') {
return data;
}
return data.sort((a, b) => {
const isAsc = sort.direction === 'asc';
switch (sort.active) {
// Add other cases (columns)
// if you are wondering where is this 'position' coming from, check the html tag for the th below
case 'position': return isAsc ?
(a.foo.position - b.foo.position > 1 ? 1 : -1) :
(a.foo.position - b.foo.position > 1 ? -1 : 1);
default: return 0;
}
});
}}
<th mat-header-cell *matHeaderCellDef mat-sort-header='position'> No. </th>