Search code examples
angularangular-material2

Disable 3rd state in Angular Material MatSortable


There are three states in sort direction of MatSortable. Is there a way to disable the 3rd state? It has 'asc' | 'desc' | '', id like to only have 'asc' | 'desc' available. I'm currently filtering the sort direction, but I'm wondering if this is intuitive enough from a users perspective to not seem like a bug even though the header does display an arrow with current sort direction(see images below).

Oninit lifecycle hook I'm setting a sort default, thought setting disableClear to true would fix this but no-go. Any help appreciated!

defaultSort: MatSortable = {
  id: 'displayName',
  start: 'asc',
  /**
   * Whether to disable the user from clearing the sort by finishing the sort direction cycle.
   * May be overriden by the MatSortable's disable clear input.
   */
  disableClear: True
};

ngOnInit() {
  this.sort.sort(this.defaultSort);

  this.sort.sortChange.pipe(
    filter(sort => !!sort.direction),
    switchMap(sort => {
      // makes API request only with an actual direction.
    })
  );
}

No sort direction: No sort direction

With sort directions: asc enter image description here


Solution

  • I'm a little unclear on your code, but it's something similar to this:

    You have this on your component

    @ViewChild(MatSort) sort: MatSort;

    and

      ngOnInit() {
        ....
        this.dataSource.sort = this.sort;
      }
    

    add this line after defining the sort

    this.sort.disableClear = true;
    

    Example Stackblitz