How to use Angular Material MatSort in a table that uses a template for header?

Viewed 243

I'm creating a custom table control to be reusable across the project. I want this table to use MatSort internally. It also must be flexible so I use templates for header and body.

The problem is that I can't specify mat-sort-header on a <th> inside a template. In my project it just doesn't work (ignores the directive). I created a simplified stackblitz and there the console shows an error: MatSortHeader must be placed within a parent element with the MatSort directive.

Here is the Stackblitz

I put there minimum amount of code to show the issue. What I want to achieve is something like this:

<my-templated-table>
  <ng-template #header>
    <tr>
      <th mat-sort-header="sortable">Sortable</th>
    </tr>
  </ng-template>
</my-templated-table>

Ideally even I'd like to have custom directive for sorting header so I can hide MatSort syntax from consumer.

I tried to find a solution for few hours now and whenever I find something similar enough it doesn't have answer. Also I've read that a directive cannot add another directive at runtime, so I don't know if my ideal approach is possible. Though I feel that both should be...

1 Answers

on html template:


<table mat-table [dataSource]="items" matSort>
 <ng-container matColumnDef="columnName">
    <th id="1" mat-header-cell *matHeaderCellDef mat-sort-header></th>
       <td mat-cell *matCellDef="let item">
         {{item.name}}
       </td>
 </ng-container>


  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

on ts file:

displayedColumns: string[] = ['columnName'];

Also you need add sort switch if required

Related