Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

  • material.angular.io

  • mat-table

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

like image 830
alphapilgrim Avatar asked Sep 20 '18 21:09

alphapilgrim


People also ask

How do I disable mat sort?

We can disable the sorting of a table in 2 ways: We can add property matSortDisabled on matSort directive, or. Add disabled attribute on any single table header.

What is matSortDisableClear?

matSortDirection: The sort direction of the currently active MatSortable. matSortDisableClear: Whether to disable the user from clearing the sort by finishing the sort direction cycle.

What is sorting in angular material table?

Angular Material provides the MatSort directive as an easy way the include interactive sorting in the tables of your application. With the MatSort directive, the user can sort the data on different columns by clicking on the column header.


2 Answers

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

like image 123
Flignats Avatar answered Oct 18 '22 23:10

Flignats


Adding the line Flignats mentioned, didn't work for me, so I had to add disableClear in the template, like:

<th mat-sort-header="firstName" disableClear>First name</th>

I hope this will help someone.

like image 32
decebal Avatar answered Oct 18 '22 22:10

decebal