Search code examples
angularangular-cdk

How to Pass CDK column and row definitions through a component


I'm trying to pass column and row definitions through a component, and I'm not sure how to do it, or if its even possible. I want to do this, so (a) the client component can specify the data, columns and rows definitions, the wrapping component can render a cdk-table plus other paging ornamentation.

<app-wrapper-table [data]="data">

  <ng-container cdkColumnDef="firstName">
    <th cdk-header-cell *cdkHeaderCellDef>First Name</th>
    <td cdk-cell *cdkCellDef="let item">{{item.firstName}}</td>
  </ng-container>

  <ng-container cdkColumnDef="lastName">
    <th appHeaderCell *cdkHeaderCellDef>Last Name</th>
    <td cdk-cell *cdkCellDef="let item">{{item.lastName}}></td>
  </ng-container>

  <ng-container cdkColumnDef="availability">
    <th appHeaderCell *cdkHeaderCellDef>Availability</th>
    <td cdk-cell *cdkCellDef="let item">{{item.availability}}></td>
  </ng-container>

  <tr cdk-header-row *cdkHeaderRowDef="displayedColumns"></tr>
  <tr cdk-row *cdkRowDef="let row; columns: displayedColumns"></tr>

</app-wrapper-table>

The wrapper table looks like this:

import { Component, OnInit, Input, TemplateRef, ContentChild, AfterViewInit } from '@angular/core';

@Component({
  selector: 'app-my-wrapper-table',
  templateUrl: './my-wrapper-table.component.html',
  styleUrls: ['./my-wrapper-table.component.scss']
})
export class MyWrapperTableComponent implements {
  @Input() data: any[];
  @ContentChild(TemplateRef) template: TemplateRef<any>;
}

<div>
  <div>Some Heading</div>
</div>
<table cdk-table [dataSource]="data">
  <ng-container [ngTemplateOutlet]="template"></ng-container>
</table>
<div class="paging-controls">
  <div class="paging-buttons">
    <button type="button">Previous</button>
    <button type="button">Next</button>
  </div>
  <div class="paging-size">
    <span>Page Size</span>
  </div>
</div>

The error I get is

Error: Missing definitions for header, footer, and row; cannot determine which columns should be rendered.

Here's a StackBlitz


Solution

  • Cdk table needs its definitions at init time, there are none if you try to provide them later on via templates or ng-content.

    Why not pull the table definition inside the content of your wrapper element and use it with an ng-content in the wrapper component like in this modified stackblitz?