rain01
rain01

Reputation: 1284

Custom Angular 6 material table component with custom columns

I'm trying to simplify creating tables with custom material table component where with very little code I can create a very custom table for each different data source with pagination and sorting already attached. All I have to pass is displayedColumns and data. Based on the examples here I built this(https://stackblitz.com/edit/angular-kp2ryv), but for some reason I'm getting error in StackBlitz when trying to use the custom column component.

ERROR TypeError: Cannot set property 'name' of undefined

Which tells me @ViewChild(MatColumnDef) columnDef: MatColumnDef; is not reading the matColumnDef in the template for some reason.

Example table creation with custom comp:

<dyn-table [data]="users" [displayedColumns]="displayedColumns">
    <dyn-col name="user_id"></dyn-col>
    <dyn-col name="user_name"></dyn-col>
</dyn-table>

Which would replace all this:

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

    <ng-container matColumnDef="user_id">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> User id </th>
        <td mat-cell *matCellDef="let data">{{ data.user_id }}</td>
    </ng-container>

    <ng-container matColumnDef="user_name">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> User name </th>
        <td mat-cell *matCellDef="let data">{{ data.user_name }}</td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
<mat-paginator #paginator [pageSize]="10"></mat-paginator>

I've spent 2 days googling and trialing and erroring and I can't figure out why it's not reading it.

Working fork of the same StackBlitz but without custom column components https://stackblitz.com/edit/angular-jw9whh

Upvotes: 4

Views: 5388

Answers (1)

yurzui
yurzui

Reputation: 214017

The reason for that is that you defined NgModule with material directives from @angular/material module but now is trying to get access to directive from @angular/material/table module.

Just a small test:

import {MatColumnDef} from '@angular/material/table';
import {MatColumnDef as RooColumnDef } from '@angular/material';

console.log(MatColumnDef, RooColumnDef, MatColumnDef === RooColumnDef);
                                                      ||
                                                     false

So as you can guess MatTableModule and MatColumnDef should be imported from the same module.

Forked Stackblitz

Upvotes: 3

Related Questions