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

Aman Sharma

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;


      .subscribe(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 matColumnDef="address">

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

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



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

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




Post a Comment

  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?

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


Post a Comment

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

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