【发布时间】:2021-08-03 00:46:37
【问题描述】:
我有一个要添加排序的垫表。我将MatSort 和mat-sort-header 标签添加到我的表/标题中,并将(MatSortChange) 事件添加到表中。我有一个行为主题作为我的数据源,在ngOnInit 我从后端获取初始数据。从那里,如果用户想要排序,他们单击排序标题,它会调用 change 事件,该事件调用我的自定义函数来对我的数据进行排序。在我的排序功能结束时,我调用behaviorSubject.next(sortedData) 并且我的表格 UI 没有更新。我在.next() 调用之前检查了该值,它是正确的。我还记录了behaviorSubject.value,这也显示了正确的数据,但表格 UI 没有更新。
表格 HTML
<div *ngIf="(this.dataSource$ | async) as dataSource">
<table mat-table [dataSource]="dataSource" matSort (matSortChange)="sortData($event)">
<ng-container matColumnDef="id">
<th mat-header-cell *matHeaderCellDef mat-sort-header> ID</th>
<td mat-cell *matCellDef="let item"> {{item.id}} </td>
</ng-container>
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Name </th>
<td mat-cell *matCellDef="let item"> {{item.name}} </td>
</ng-container>
<ng-container matColumnDef="date">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Date</th>
<td mat-cell *matCellDef="let item"> {{item.date | date: 'MM/dd/yyyy'}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</div>
组件.ts
dataSource$: BehaviorSubject<Person[]> = new BehaviorSubject([]);
...
ngOnInit(): void {
this.service.getData().subscribe((val) => this.dataSource$.next(val));
sortData(event: MatSort) {
const columnToSort = event.active;
const direction = event.direction === 'asc' ? 1 : -1;
const data = this.dataSource$.value;
data.sort((a, b) => {
if(a[columnToSort] < b[columnToSort]) {
return -1 * direction;
} else {
return 1 * direction;
}
});
this.dataSource$.next(data);
}
【问题讨论】:
-
你是否通过多次点击检查是否正在重置方向?可能方向设置为“”。您可以检查 matSort 元素上的 matSortDisableClear 属性。 - 为防止用户从已排序的列中清除排序状态,请在 matSort 上将 matSortDisableClear 设置为 true 以影响所有标题,或在特定标题上将 disableClear 设置为 true。
标签: angular mat-table behaviorsubject