[Table] Add example with dynamic columns
Bug, feature request, or proposal:
Proposal
What is the expected behavior?
It'd be nice to have example(s) on how to use md-table with dynamic columns.
What is the current behavior?
Currently all the examples are with hard coded columns, like this:
<!-- ID Column -->
<ng-container cdkColumnDef="userId">
<md-header-cell *cdkHeaderCellDef md-sort-header> ID </md-header-cell>
<md-cell *cdkCellDef="let row"> {{row.id}} </md-cell>
</ng-container>
<!-- Progress Column -->
<ng-container cdkColumnDef="progress">
<md-header-cell *cdkHeaderCellDef md-sort-header> Progress </md-header-cell>
<md-cell *cdkCellDef="let row"> {{row.progress}}% </md-cell>
</ng-container>
@andrewseguin
For those interested, here was my approach
https://plnkr.co/edit/UntMipJO7lQVFCCSq3sZ?p=preview
<!-- Generic column definition -->
<ng-container *ngFor="let column of columns" [cdkColumnDef]="column.columnDef">
<md-header-cell *cdkHeaderCellDef>{{ column.header }}</md-header-cell>
<md-cell *cdkCellDef="let row">{{ column.cell(row) }}</md-cell>
</ng-container>
/** Table columns */
columns = [
{ columnDef: 'userId', header: 'ID', cell: (row: UserData) => `${row.id}` },
{ columnDef: 'userName', header: 'Name', cell: (row: UserData) => `${row.name}` },
{ columnDef: 'progress', header: 'Progress', cell: (row: UserData) => `${row.progress}%` }
];
/** Column definitions in order */
displayedColumns = this.columns.map(x => x.columnDef);
EDIT: Here is a (hopefully) evergreen stackblitz with the exact same approach
https://stackblitz.com/edit/material2-beta11-vmwjpe
Is it possible to internationalize these dynamic columns implementation?
I wonder what you refer to when you say "dynamic"? Many things regarding columns can be dynamic. If your goal is to dynamically change which columns are shown then I think the simplest approach is to change displayedColumns.
I think he outlined it pretty well here:
//----- What is the current behavior? Currently all the examples are with hard coded columns, like this: //-----
What he (and myself) are looking for is the ability to render an arbitrary number of columns with heading names taken from some underlying datasource, e.g. columns: ColumnDefinition[];
It has to be said that the current mechanism for binding md-table to a dataSource is dreadful. It should be consistent with how we *ngFor over collections to render results, only in this instance, stamp out column definitions. Same story for rows.
Hi @willshowell. Thanks, just looking at how you approached this. I'm not sure why but the Plunker you created has stopped working.
@eltimmo updated the original comment!
Can't seem to get this working in beta 12. Always get error that cdk-table can't find column with id.
Also, if I am using the MatTableModule, do I need to pull in the CdkTableModule?
It seems that there is an issue with using dynamic columns inside the ng-bootstrap modal. As neither the ngx-bootstrap modal and the material2 modal seem to work when lazy loaded, I'm using ng-bootstrap. It seems that the ContentChildren don't include column defs when using *ngFor.
Well, looks like I am wrong. I was able to create this Stackblitz and it works, so not sure why its failing for me locally. Ugh
PEBCAK
From Will's example, I created this. I'm looking forward to simple tables being implemented :-) https://stackblitz.com/edit/angular-dynamic-tables
Hi, I was looking for how to write generic code to implement the pagination,filtering and sorting. Thanks
Has this support for dynamic columns made it into a stable release? I'm trying to implement this and I'm not sure whether I'm doing something wrong, or whether my use case just isn't supported. I'd like to load arbitrary data from a CSV, detect column headers at runtime, and show that in a table.
<mat-table *ngIf="data" [dataSource]="data">
<ng-container *ngFor="let column of columns" [matColumnDef]="column">
<mat-header-cell *matHeaderCellDef>{{ column }}</mat-header-cell>
<mat-cell *matCellDef="let row">{{ row[column] }}</mat-cell>
</ng-container>
</mat-table>
const rows = [
{"id": "1", "name": "Macaw, scarlet", "lat": "31.215291", "lng": "118.931012"},
{"id": "2", "name": "Armadillo, nine-banded", "lat": "35.663752", "lng": "103.389346"},
{"id": "3", "name": "Greater roadrunner", "lat": "13.17535", "lng": "44.27461"},
{"id": "4", "name": "Goanna lizard", "lat": "22.671042", "lng": "113.823131"},
{"id": "5", "name": "Cape starling", "lat": "16.0213558", "lng": "100.417181"}
];
const columns = Array<string> (Object.keys(rows[0]));
const data = new MatTableDataSource<Object>(rows);
Result:
AppComponent.html:31 ERROR Error: Missing definitions for header and row, cannot determine which columns should be rendered.
at getTableMissingRowDefsError (table.es5.js:363)
at MatTable.CdkTable.ngAfterContentInit (table.es5.js:512)
at callProviderLifecycles (core.js:12422)
at callElementProvidersLifecycles (core.js:12399)
at callLifecycleHooksChildrenFirst (core.js:12383)
at checkAndUpdateView (core.js:13511)
at callViewAction (core.js:13858)
at execEmbeddedViewsAction (core.js:13816)
at checkAndUpdateView (core.js:13509)
at callViewAction (core.js:13858)
EDIT: The problem was that I needed to include the following, inside of <mat-table/>:
<mat-header-row *matHeaderRowDef="columns"></mat-header-row>
<mat-row *matRowDef="let row; columns: columns;"></mat-row>
@donmccurdy Looks like you're all set except you are missing definitions for <mat-row> and <mat-header-row> where you will define which columns to display
@andrewseguin thanks! That was exactly it. 🙂
Hi
Has anyone tried this with sorting enabled?
columnSetup = [
{
def: 'name',
title: 'Name',
displayFcn: (item: Item) => item.name,
sort: true
}
];
<mat-table #table [dataSource]="tableData" matSort>
<ng-container *ngFor="let column of columnSetup" matColumnDef="{{ column.def }}">
<mat-header-cell *matHeaderCellDef [attr.mat-sort-header]="column.sort ? column.def : null">{{ column.title }}</mat-header-cell>
<mat-cell *matCellDef="let item"> {{ column.displayFcn(item) }} </mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns()"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns();"></mat-row>
</mat-table>
When this compiles, mat-sort-header="true" renders correctly in <mat-header-cell>, however the sort functionality doesn't work.
Any suggestions appreciated!
@boombard , I've tried you template code. [attr.mat-sort-header]="column.sort ? column.def : null" => not work [mat-sort-header]="column.sort ? column.def : null"
It looks the binding you use => [attr.mat-sort-header] is bind to the DOM, not a property binding. https://angular.io/guide/template-syntax#binding-targets
@boombard I tried different property bindings and I couldn't get it to work. I found that if you add "disabled" attribute it disables it, but other than using *ngIf I didn't find a way to conditionally emit the disabled attribute.
Conditionally sortable columns (works fine in a dynamic column loop too)
<div *ngIf="sortable">
<mat-header-cell *matHeaderCellDef mat-sort-header> No. </mat-header-cell>
</div>
<div *ngIf="!sortable">
<mat-header-cell *matHeaderCellDef mat-sort-header disabled> No. </mat-header-cell>
</div>
@nothingisnecessary Thanks for the suggestion, in the end I also went with *ngIf - seems like the only option
Jeee! This is not added to the docs yet?