如何对顶部带有收藏夹的材料表进行排序?



我想在 Angular 中对一个mat-table(或搜索引擎的MatTable)进行排序,并将"收藏夹"项目放在顶部。

我希望无论当前设置什么排序,最喜欢的项目始终是表的第一个项目。

我查了互联网,但一无所获,所以我不得不自己做。

这是我的解决方案: https://stackblitz.com/edit/angular-defaultsort-zgwgpv

以下是实现的主要部分。

将排序重定向到名为sortData的方法。在这里,我可以根据需要对数据进行排序:

<table
matSort
(matSortChange)="sortData($event)"
matSortActive="carbs"
matSortDirection="asc"
>

此方法处理sort变量并调用该方法sortIt

sortData(sort: Sort) {
const data = this.desserts.slice();
if (!sort.active || sort.direction === '') {
// initially
this.sortIt('', true, data);
return;
}
this.sortIt(sort.active, sort.direction === 'asc', data);
}

sortIt方法对所需的比较器进行排序和调用。最主要的是,我检查了 3 种不同的状态:两个项目都是收藏夹(在"顶部"收藏夹部分排序),只有一个项目是收藏夹(在这种情况下,收藏夹是"在"正常"项目之前),第三个是当两个项目都是"正常"项目时,在这种情况下我按不同的属性排序。

sortIt(property: string, isAsc: boolean, data: Dessert[]): void {
this.sortedData = data.sort((a, b) => {
if (FAVORITES_FIRST) {
if (a.favorite && b.favorite) {
return this.sortByBothFavorites(property, isAsc, a, b);
}
// if only one favorite, the favorite is on top, no matter asc or desc
if (a.favorite === true) {
return -1;
} else if (b.favorite === true) {
return 1;
}
}
// if no favorite, standard sorting
return this.stdSort(property, isAsc, a, b);
});
}

这就是诀窍!玩得开心!

最新更新