2 of 2
solution
tprieboj
  • 1.7k
  • 6
  • 31
  • 55

Angular material 2 table - define column using TemplateRef and ngTemplateOutlet

I am trying to make reusable material table and I want to use TemplateRef with ngTemplateOutlet to generate columns. In this example I created cards components which is using my material-table component. In cards.component.html I have template of one of my table's column. Running the project will cause an error ERROR TypeError: Cannot read property 'template' of undefined (see console on stackblitz). Is it possible to pass columnt template to my MaterialTableComponent and use it to define column?

 <table mat-table [dataSource]="data" class="mat-elevation-z4">
  <ng-container
    *ngFor="let column of displayedColumnObjects"
    [matColumnDef]="column.id"
  >
  <!-- if where is cellTemplate in table config json, use cellTemplate  -->
    <ng-container
      *ngIf="column.cellTemplate" 
      [ngTemplateOutlet]="column.cellTemplate"
    >
    </ng-container>

    <ng-container *ngIf="!column.cellTemplate">
      <th mat-header-cell *matHeaderCellDef> {{column.title}} </th>
      <td mat-cell *matCellDef="let element"> {{element[column.id]}} </td>
    </ng-container>
  
  </ng-container>

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

UPDATE I found solution using ngTemplateOutletContext.

<table mat-table [dataSource]="data" class="mat-elevation-z4">
  <ng-container
    *ngFor="let column of displayedColumnObjects"
    [matColumnDef]="column.id"
  >
  
    <ng-container
      *ngIf="column.cellTemplate"
    >
      <th mat-header-cell *matHeaderCellDef> {{column.title}} </th>
      <td mat-cell *matCellDef="let element"> 
        <ng-template
          [ngTemplateOutletContext]="{
            element: element[column.id]
          }"
          [ngTemplateOutlet]="column.cellTemplate">
        </ng-template>
      </td>
    </ng-container>

    <ng-container *ngIf="!column.cellTemplate">
      <th mat-header-cell *matHeaderCellDef> {{column.title}} </th>
      <td mat-cell *matCellDef="let element"> {{element[column.id]}} </td>
    </ng-container>
  
  </ng-container>

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

See my example

tprieboj
  • 1.7k
  • 6
  • 31
  • 55