Angular material 2 table - define column using TemplateRef and ngTemplateOutlet

房东的猫 提交于 2020-02-23 11:53:49

问题


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

来源:https://stackoverflow.com/questions/52812422/angular-material-2-table-define-column-using-templateref-and-ngtemplateoutlet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!