【发布时间】:2021-12-30 04:12:07
【问题描述】:
我想将材料表的排序存储在本地或会话存储中。因为我在不同的页面上有多个表格,所以应该为每个页面保存排序值。
【问题讨论】:
-
到目前为止您尝试过什么,为什么这对您不起作用?你能分享一些你的代码和它的行为吗?
标签: angular angular-material angular-directive
我想将材料表的排序存储在本地或会话存储中。因为我在不同的页面上有多个表格,所以应该为每个页面保存排序值。
【问题讨论】:
标签: angular angular-material angular-directive
我为此创建了一个自定义指令。基本上,唯一需要保存的值是排序列的 id 和排序 direction。我已经定义了一个定义这两个值的接口 MatSortData。为了根据页面保存状态,路径名被添加到键中。
如果您想将值保存在 localStorage 中,只需将其替换为 sessionStorage 变量即可。
const KEY = 'MAT_SORT';
@Directive({
selector: '[sortingCache]'
})
export class SortingDirective {
get matSort(): MatSortData {
return JSON.parse(sessionStorage.getItem(window.location.pathname + '?' + KEY));
}
set matSort(mat: MatSortData) {
sessionStorage.setItem(window.location.pathname + '?' + KEY, JSON.stringify(mat));
}
constructor(
private el: MatSort,
) {}
ngOnInit(): void {
if(this.matSort) {
this.el.active = this.matSort.active;
this.el.direction = this.matSort.direction;
}
this.el.sortChange.subscribe((sort: Sort) => {
this.matSort = {
active: sort.active,
direction: sort.direction
}
});
}
}
interface MatSortData {
active: string;
direction: SortDirection;
}
该指令只需添加到一个排序标头即可工作。示例 html:
<ng-container matColumnDef="example">
<mat-header-cell
sortingCache
mat-header-cell
*matHeaderCellDef
mat-sort-header
>
Example Header
</mat-header-cell>
<mat-cell mat-cell *matCellDef="let element"></mat-cell>
</ng-container>
【讨论】: