Angular Material MatTable Data Sorting

Angular Material MatTable Provides great flexibility to perform multiple operations on data. you can easily apply filter, sorting, pagination and many more features.

You can use default feature or you can also override default features and create custom as per your need. 

Here we are focusing on MatTable data Sorting.

you  need some data on which user can apply sorting, so let's checkout TheBitOps another article Bind data to MatTable Angular Material


export class EmployeeComponent implements OnInit {
  dataSource = new MatTableDataSource();
  @ViewChild(MatSort) sort: MatSort;
  constructor(){}

  ngOnInit(): void {
    this.dataSource.data = data; // data come from service or from a file
    this.dataSource.sort = this.sort;   // this line of code will handle sorting of data
  }
}

 

In Html you need to add matSort and mat-sort-header


<table mat-table matSort [dataSource]="dataSource" class="mat-elevation-z8">

  <ng-container matColumnDef="id">
    <th mat-header-cell *matHeaderCellDef mat-sort-header > ID </th>
    <td mat-cell *matCellDef="let element"> {{element.id}} </td>
  </ng-container>
</table>

Now build your project and check in browser, if you click on table header, you can see data sorting on mat table.

if you want to add custom sorting with sorting column and sorting direction from your component, check out below code.


      const sortState: Sort = {active: 'column-name', direction: 'asc/desc'};
      this.sort.direction = sortState.direction;
      this.sort.sortChange.emit(sortState);

I hope it can help you..., Please write down below to improve this article or have any query.

Enjoy Coding :)

Leave a comment

your email address will not be published. required fields are marked *

Name *
Email *
Phone