Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default sorting in Angular Material with nested objects

Im using mat table with sorting, where I want to set default sorting on a certain column.

This works for plain attributes but not for nested ones.

Here is my table

<table mat-table [dataSource]="dataSource" multiTemplateDataRows 
       matSort matSortActive="break" matSortDirection="asc"
       class="mat-elevation-z4 w-100">

My nested sorting

this.dataSource.sort = this.sort;
   this.dataSource.sortingDataAccessor = (item, property) => {
   switch(property) {
      case 'break': return item.break.start;
      default: return item[property];
   }
};

Also this nested sorting is fine, when you are manually clicking on the header to sort, it does what I expect but on default it doesn't sort, only shows the sorting arrow.

That's how it looks like on page load:

Here is the corresponding stackblitz.

like image 778
Norbert Bartko Avatar asked Mar 19 '26 07:03

Norbert Bartko


1 Answers

The initial sorting didn't work properly when i researched it in may.

In my case it was necessary to write my own setSortHeader function that executes after getting data.

setSortHeader() {
  this.sort.active = 'break';
  this.sort.direction = 'desc';
  this.sort.sortChange.emit({ active: this.sort.active, direction: this.sort.direction });

  const sortHeader = this.sort.sortables.get('break');
  if (sortHeader) sortHeader['_setAnimationTransitionState']({ toState: 'active' });
}

I'm not sure that this code still necessary but in my case that worked.

like image 50
vadjs Avatar answered Mar 25 '26 23:03

vadjs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!