Cannot read properties of undefined (reading ‘template’) at matheaderrowdef.extractcelltemplate

Usually, this error occurs when you are trying to access the ‘template’ property of an undefined object. The error message specifically points to the matheaderrowdef.extractcelltemplate function.

To understand this error, let’s consider an example. Imagine you have an Angular application using the Material Design table component. You define the table structure in your component template file like this:

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

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

In this example, the issue could arise if the displayedColumns array is not defined or if it is empty. The displayedColumns array is used to define which columns should be displayed in the table rows. If this array is undefined or empty, the matHeaderRowDef function cannot read the ‘template’ property of it, resulting in the mentioned error.

To fix this error, you need to make sure that the displayedColumns array is properly defined and has at least one column defined in it. For example:

export class YourComponent {
  displayedColumns: string[] = ['id', 'name', 'email'];
  // ...
}

In this updated example, we have defined the displayedColumns array with three column names: ‘id’, ‘name’, and ’email’. Now, the matheaderrowdef.extractcelltemplate function will be able to access the ‘template’ property of the displayedColumns array without any errors.

Read more

Leave a comment