5

I have a question about the use of MatSort.sortChange from Angular Material.

Configuration

  • angular 5.0.2.
  • angular/cdk": "^5.0.0-rc0"
  • angular material 5.0.0-rc0

Context

I have a component that includes a mat-table and some buttons. When the user click on some buttons the table should be reset to its initial state. In particular, I want to reset the sort order to 'asc'.

Problematic

  • Basically, my solution to achieve that was to emit a new Sort with the desired properties through MatSort.sortChange AND manually update MatSort.direction
    • The sort reset does not work if one of the two operations is not included

Question

  • I thought that just emitting a sortChange would be sufficient
  • Am I doing something wrong ?
  • Is there a better solution than the one provided below?

Thanks in advance for youre help! :)

Relevants parts of my Code

export class RoleMembersComponent implements OnInit, OnChanges {

@ViewChild('inputfilter') inputfilter: ElementRef;  
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;

ngOnInit() {
    // bug#5593 START: Added this.changeDetector.detectChanges();
    this.changeDetector.detectChanges();
    // bug#5593 END
    this.dataSource = new RoleMemberDatasource(this.database, this.paginator, this.sort);    
    this.onUserInteractionsWithTable();    
}


private onUserInteractionsWithTable () {
    const tableUserActionsListener = [
        this._inputFilterChange,
        this.paginator.page,
        this.sort.sortChange
    ];    
    mergeOfObservables.subscribe((data : any) => {
        // If internal sort do not load data again
        // because reset of _inputFilterChange already trigger reload.
        if (!this.isResetSort(data)) {
            this.loadData();
        } else {
            this.sort.direction = data.direction;            
        }
    }); 
}

private resetSort () {
    // TODO: The content of sort seems to be ignored.
    const sort    = <Sort>{
            active: this.defaultSortActiveFld, // works even if I put 'dummy'
            direction: this.defaultSortDirection,
            resetSort: true
        };
    this.sort.sortChange.emit(sort);
}

private isResetSort(obj: any): boolean {
    return (obj.resetSort);
}
4

1 回答 1

0

我发现修改 dataSource 排序active然后direction强制更新是可行的。

this.dataSource.sort.active = 'columnName';
this.dataSource.sort.direction = null; // reset or 'asc' / 'desc'
this.dataSource._updateChangeSubscription(); // force update table
于 2021-12-03T16:22:41.080 回答