Dejan S
Dejan S

Reputation: 1851

Dynamic header content in Angular Material Table?

Im trying to add a dynamic header to my angular material table, but I cant figure out how to do it. I want the month to be in the header in this case.

<ng-container matColumnDef="month">
    <th mat-header-cell *matHeaderCellDef> {{element.month}} </th>
    <td mat-cell *matCellDef="let element"> {{element.hours}} </td>
</ng-container>

I also tried *matHeaderCellDef="let element" but its not working. I keep getting the error:

TypeError: Cannot read property 'month' of undefined

Any ideas?

Upvotes: 6

Views: 3278

Answers (1)

umutesen
umutesen

Reputation: 2640

You can't define variable like *matHeaderCellDef="let element" because the header text must not be undefined when the table is initialised.

You need to ensure the table is not initialised until you get the month value.

e.g. use *ngIf="data" so that the table is not initialised until table source has values.

Assuming month value is loaded through HTTP and stored in retrievedMonth,

You can populate the header dynamically like so:

<th mat-header-cell *matHeaderCellDef> {{retrievedMonth}} </th>

If the month value is in an array or in the same data source as the table, you need to put some filtering logic to extract the month value.

Upvotes: 4

Related Questions