Sorting Nested Data in Material Table (Mat Table) in angular 6/7/8.

Aman Sharma
3


In  Mat tables in angular (6,7,8 etc), we can sort data easily using MatSort. Issue occurs when we need to sort nested data coming from API. In following code snippet, I have explained how we can sort MAT table with nested data.

Component.ts File:

 

loadUserDetails() {

    this.status = status;

    this.userService.getDetail()

      .subscribe(data => {

        this.dataSource.data = data;

        this.dataSource.paginator = this.paginator;

        this.dataSource.sort = this.sort;       

        

        this.dataSource.sortingDataAccessor = (item, property) => 

          switch (property) {            

            case 'userName': return item.user.userName;         

            default: return item[property];

          }

        };

      });

  }

 

 

In Above snippet, datasource is a MatDataSource, that accepts a client-side data array and includes native support of filtering, sorting (using MatSort), and pagination (using MatPaginator).

 

Allows for sort customization by overriding sortingDataAccessor, which defines how data properties are accessed. Also allows for filter customization by overriding filterTermAccessor, which defines how row data is converted to a string for filter matching.

 

We will use switch statement to sort particular nested column, for others default statement will execute.

 

Component.html File:

 

<mat-table #table [dataSource]="dataSource" matSort class="table table-hover table-bordered mb-0 crew-table table-striped">      

 

      <ng-container matColumnDef="userName">

        <mat-header-cell *matHeaderCellDef mat-sort-header>User</mat-header-cell>

        <mat-cell *matCellDef="let row"> {{row.user?.userName}}</mat-cell>

      </ng-container>

 

      <ng-container matColumnDef="address">

        <mat-header-cell *matHeaderCellDef mat-sort-header>Address</mat-header-cell>

        <mat-cell *matCellDef="let row"> {{row.address}}</mat-cell>

      </ng-container>

 

       <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>

      <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>

    </mat-table>

 

  

Post a Comment

3Comments
  1. Excellent I spent 2 days trying to figure this out. Thank you!! I am having the same problem with filtering do you have a solution for that?

    ReplyDelete
    Replies
    1. Sorry for late reply.. Do you still need help in filtering for nested data? Please let me know..

      Delete
    2. https://www.netdeft.com/2022/02/filter-nested-data-in-angular-8.html

      Delete
Post a Comment

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !