[Fixed] Material Sort not working when there are null objects

Issue

I made a code that adds empty rows if the rows are less than 5 but now the sort function is not working. When I remove the for loop it works but when I put it back it doesnt. Is there any way to fix this?

        this.userData = data.info;
        //when i remove this if condition the sorting works
        if(this.userData.length <=5){
          for (let index = 0; index <= 6 - this.userData.length; index++) {
              this.userData.push(Object.create(null));
          }
        }
        this.dataSource = new MatTableDataSource(this.userData);
        this.dataSource.sort = this.sort;
        this.dataSource.paginator = this.paginator;

I really need the table to have empty rows so I’m stuck

Solution

I would start by changing the if and for loop with a while loop.

while(this.userData.length <=5){
   this.userData.push(Object.create(null));
}

Then sort the data before adding it to the MatTableDataSource. This function will sort the ‘userData’ Object by using its ‘name’ property. And send null objects to the back.

this.userData.sort((a,b) => (b.name) ? ((a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0)) : -1);

If you want to let the user change the sorting you should bind to the matSortChange event of your mat-table.

<mat-table (matSortChange)="onSortChange($event)">

And re-sort every time this event is called.

onSortChange(sort: MatSort): void {
   const data: Array<UserData> = this.dataSource.data.slice();
   if (!sort.active || sort.direction === '') {
      this.dataSource.data = data;
      return;
   }

   this.dataSource.data = data.sort((a, b) => {
      let isAsc: boolean = sort.direction === 'asc';
      let valSortProperty = sort.active;
      return b[valSortProperty] ? this.compare(a[valSortProperty], b[valSortProperty], isAsc) : -1;
   });

   this.dataSource = new MatTableDataSource<UserData>(this.dataSource.data);
   this.dataSource.paginator = this.paginator;
}

compare(a: any, b: any, isAsc: boolean): number {
   if(isAsc){
      return (a > b) ? 1 : ((b > a) ? -1 : 0)
   } else {
      return (a < b) ? 1 : ((b < a) ? -1 : 0)
   }
}

Leave a Reply

(*) Required, Your email will not be published