Default sorting in Angular Material - Sort header

后端 未结 9 1298
执念已碎
执念已碎 2020-12-13 03:14

How can I change Angular Material code below, so that data-table is sorted by \'name\' column, ascending order by default. Arrow (indicating current sort direction) must be

相关标签:
9条回答
  • 2020-12-13 03:58
    @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);
    

    should work. demo

    And to show sorting direction arrow, add next css (workaround)

    th.mat-header-cell .mat-sort-header-container.mat-sort-header-sorted .mat-sort-header-arrow {
        opacity: 1 !important;
        transform: translateY(0) !important;
    }
    
    0 讨论(0)
  • 2020-12-13 03:59

    You're mistaking matSortStart for matSortDirection.

    Try this:

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

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

    matSortStart can be used to reverse the cycle used when sort (e.g. when the user clicks to sort, it starts at desc instead of asc).

    0 讨论(0)
  • 2020-12-13 04:06

    You can programmatically sort the table by invoking the sort(Sortable) method of the data source. Assuming you've got a dataSource component property for the data source:

    // 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;
    
    0 讨论(0)
提交回复
热议问题