12
votes

After i specify the mat-sort-header attribute on matHeaderCellDef to create a Sortable table in Angular Material, getting the following error

MatSortHeader must be placed within a parent element with the MatSort directive.

<mat-table #table matSort [dataSource]="myHttpDataSource">
....
<ng-container matColumnDef="myColumnName">
<mat-header-cell *matHeaderCellDef mat-sort-header></mat-header-cell>
<mat-cell *matCellDef="let row"> {{row.somedetails}} </mat-cell>
</ng-container>
</mat-table>

Any pointers/help appreciated

4
Did you import the MatSortModule ? - user4676340
Yes i added MatSortModule in both app-material.ts as well as in app.module.ts - RajeshTV

4 Answers

33
votes

Add 'matSort' attribute to mat-table

<mat-table #table [dataSource]="dataSource" matSort>
</mat-table>
7
votes

<mat-table mat-table [dataSource]="dataSource" matSort>

    <ng-container matColumnDef="name">
      <th mat-header-cell *matHeaderCellDef mat-sort-header> Name </th>
      <td mat-cell *matCellDef="let element"> {{element.name}} </td>
    </ng-container>
To add sorting behavior to the table, add the matSort directive to the 
table and add mat-sort-header to each column header cell that should 
trigger sorting.
0
votes

could you give us more info please?

have you try catch the event?

<mat-table #table [dataSource]="dataSource" matSort (matSortChange)="sortData($event)">
-2
votes

Realized that I was using the old mdSort tag in another mat-table which was causing this issue. After changing to matSort the issue got resolved.