Angular Material中的默认排序 - 排序标题

问题描述 投票:23回答:4

如何更改下面的Angular Material代码,以便数据表按'name'列排序,默认按升序排序。必须显示箭头(表示当前排序方向)。

这就是我想要实现的目标:

enter image description here

原始代码:

<table matSort (matSortChange)="sortData($event)">
  <tr>
    <th mat-sort-header="name">Dessert (100g)</th>
    <th mat-sort-header="calories">Calories</th>
    <th mat-sort-header="fat">Fat (g)</th>
    <th mat-sort-header="carbs">Carbs (g)</th>
    <th mat-sort-header="protein">Protein (g)</th>
  </tr>

  <tr *ngFor="let dessert of sortedData">
    <td>{{dessert.name}}</td>
    <td>{{dessert.calories}}</td>
    <td>{{dessert.fat}}</td>
    <td>{{dessert.carbs}}</td>
    <td>{{dessert.protein}}</td>
  </tr>
</table>

我正在尝试这样的东西,但它不起作用(没有箭头显示,没有排序)

<table matSort (matSortChange)="sortData($event)" matSortActive="name" matSortStart="asc" matSortDisableClear>

这里是Plunker的链接

angular angular-material
4个回答
57
投票

你把matSortStart误认为matSortDirection

试试这个:

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

https://plnkr.co/edit/sg0hC5d8LTjLKhbH9Eug?p=preview

matSortStart可用于反转排序时使用的循环(例如,当用户点击进行排序时,它从desc而不是asc开始)。


15
投票

您可以通过调用数据源的sort(Sortable)方法以编程方式对表进行排序。假设您有数据源的dataSource组件属性:

// to put next to the class fields of the component
@ViewChild(MatSort) sort: MatSort

// to put where you want the sort to be programmatically triggered, for example inside ngOnInit
this.sort.sort(({ id: 'name', start: 'asc'}) as MatSortable);
this.dataSource.sort = this.sort;

5
投票
@ViewChild(MatSort) sort: MatSort;

this.dataSource.sort = this.sort;

const sortState: Sort = {active: 'name', direction: 'desc'};
this.sort.active = sortState.active;
this.sort.direction = sortState.direction;
this.sort.sortChange.emit(sortState);

应该管用。 demo

并显示排序方向箭头,添加下一个css(解决方法)

th.mat-header-cell .mat-sort-header-container.mat-sort-header-sorted .mat-sort-header-arrow {
    opacity: 1 !important;
    transform: translateY(0) !important;
}

1
投票

也许你试图在页面的init上调用名称和方向强制的排序功能?

     ngOnInit() {
    let defSort: Sort = {};
    defSort.direction = 'asc';
    defSort.active = 'name';
    this.sortData(defSort);
  }
© www.soinside.com 2019 - 2024. All rights reserved.