Skip to content

[Table] Add example with dynamic columns #5927

Closed

Description

@rafaelss95

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

Activity

  1. willshowell commented on Jul 21, 2017

    @willshowell
    Contributor

    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

  2. self-assigned this
    on Jul 21, 2017
  3. alexrun commented on Jul 30, 2017

    @alexrun

    Is it possible to internationalize these dynamic columns implementation?

  4. pueaau commented on Aug 9, 2017

    @pueaau

    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.

  5. sophistyx commented on Sep 4, 2017

    @sophistyx

    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.

  6. eltimmo commented on Oct 5, 2017

    @eltimmo

    Hi @willshowell. Thanks, just looking at how you approached this. I'm not sure why but the Plunker you created has stopped working.

  7. willshowell commented on Oct 5, 2017

    @willshowell
    Contributor

    @eltimmo updated the original comment!

  8. added
    docs
    P4
    and removed on Oct 19, 2017
  9. jscharett commented on Oct 30, 2017

    @jscharett

    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?

  10. jscharett commented on Oct 30, 2017

    @jscharett

    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.

  11. jscharett commented on Oct 30, 2017

    @jscharett

    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

  12. jscharett commented on Oct 30, 2017

    @jscharett

    PEBCAK

  13. 37 remaining items

  14. andrewseguin commented on May 20, 2019

    @andrewseguin
    Contributor

    Hey @nasreddineskandrani - looks like a neat way of doing dynamic components. I think if we had such a feature, it would likely go the route of using CdkPortal. That said, we don't currently have plans on bringing something like this into the repository right now

  15. plixxer commented on Aug 7, 2019

    @plixxer

    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

    Thank you good Sir, I am converting a bootstrap UI to a material UI and i was stuck on this for quite some time.

  16. lonnenjunior commented on Oct 25, 2019

    @lonnenjunior

    @fxck CdkTable has addColumnDef and removeColumnDef methods. It's a little clunky to use, but I think it does what you need

    https://stackblitz.com/edit/angular-i4dftq?file=app/cdk-table.ts

    @willshowell Thanks for this answer it helped me a lot. Currently I'm trying to create a generic data table where I pass only the matColumnDef and everything else is done automaticaly (Paginator, Selection, ...) Unfortunately, there is no possibility to add the mat-sort-header using the addColumn function. Is there any other possibility to do it?

    https://stackblitz.com/edit/angular-i4dftq-urhcpg

  17. isaif commented on Nov 8, 2019

    @isaif

    @paco76

    Note I just copy-pasted syntax from my original comment. It's from an outdated beta version of Material and should be updated to the current syntax

    <!-- Button column -->
    <ng-container ... ></>
    
    <!-- Checkbox column -->
    <ng-container ... ></>
    
    <!-- Generic column definition for dynamic columns -->
    <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>
    
    /** Static columns */
    staticColumns = ['button', 'checkbox'];
    
    /** Dynamically generated columns */
    dynamicColumns = [
      { 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.staticColumns, ...this.columns.map(x => x.columnDef)];

    this works but the index of static columns is returned as undefined. Do you have any idea on how to solve this?

  18. iamsank8 commented on Apr 10, 2020

    @iamsank8

    I was able to use this approach to add dynamic columns to my table by specifying template from parent. However, I was not able to add pipes to template.

    { field: 'date', label: 'Date', template: (row: any) => ${row['date']} }
    I want to add date pipe to this column.

    This is how I am rendering cell definition.
    <mat-cell *matCellDef="let row"><div [innerHTML]="column.template(row)"></div></mat-cell>

    UPDATE
    I was able to find this example which used implementation of pipe. It is working for me.
    Link to My Savior

  19. tadlakha9 commented on May 22, 2020

    @tadlakha9

    Check out this link to create the Angular Datatable(P-Table) with Dynamic Columns, pagination, sorting, column level filtering, Reordering and Resizing of Column

    https://www.youtube.com/watch?v=zDvzBK-xyAM

  20. parijat93sharma commented on Aug 27, 2020

    @parijat93sharma

    i am still stuck at something like this,My Table has no headers and the first column of the table is like the header.
    I need a mat-table which will have columns based on an array of Object and each column will have 4 normal textfields and 8 dropdowns,and these will be pre filled with some data or empty depending on the array of Object;

    Something like this

    MY DATASOURCE AT FIRST WILL HAVE ONLY

    dataSource =[{label:'Name'}
    {'label':Hobby},{'label':Address},
    {'label:'state'}];

    Name | Arnold | Berrry | Pickachu

    hobby | Football | Baseball | Cricket

    Address | dropdown | dropdown | dropdown

    State | multiselect | multiselect | multiselect

    CAN ANYONE PLEASE HELP ME WITH THIS APPROACH ??? @isaif @paco76 @plixxer @iamsank8

    I also need to insert Columns on click of a button at a later time,Now the problem is i will have to insert a key:Value pair in each of the objects and those keys should also be dynamic otherswise it will be a duplicate

  21. kargozerov commented on Nov 5, 2020

    @kargozerov
          <ng-container *ngFor="let column of columns" [cdkColumnDef]="column.columnDef">
            <mat-header-cell *cdkHeaderCellDef>{{ column.header }}</mat-header-cell>
            <mat-cell *cdkCellDef="let row" >{{ row[column.columnDef] }}</mat-cell>
          </ng-container>
    
      columns = [
        { columnDef: 'position', header: 'No.'},
        { columnDef: 'name',     header: 'Name'},
        { columnDef: 'weight',   header: 'Weight'},
        { columnDef: 'symbol',   header: 'ТЕСТ'},
      ];
    
    const row = [
      {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
      {position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'},
      {position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'},
      {position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be'},
    ];
    
  22. Khaaz commented on May 27, 2021

    @Khaaz

    I know this was marked as closed, but I have issues with this.
    While I am able to have dynamic columns like this working perfectly, mat-sort-header doesn't work with it.
    Apparently, if I declare each column individually it works, if I do it with the above syntax, it created the columns dynamically but the sorting doesn't work. It actually doesn't even show the sorting arrows.

    <table mat-table [dataSource]="dataSource" matSort>
    			
    	<ng-container *ngFor="let column of columns" [matColumnDef]="column.def" >
    		<th mat-header-cell *matHeaderCellDef> {{column.header}} </th>
    		<td mat-cell *matCellDef="let element"> {{column.render(element)}} </td>
    	</ng-container>
    	<tr mat-header-row *matHeaderRowDef="columnDefs"></tr>
    	<tr mat-row *matRowDef="let row; columns: columnDefs;"></tr>
    </table>
    columns = [
    	{ def: "id", header: "ID", render: (d: Quotation): number => d.id },
    	{ def: "name", header: "Devis", render: (d: Quotation): string => d.name },
    	{ def: "client", header: "Client", render: (d: Quotation): string => d.client },
    	{ def: "project", header: "Projet", render: (d: Quotation): string => d.project },
    ];
    
    get columnDefs(): string[] {
    	return this.columns.map(e => e.def);
    }
  23. andrewseguin commented on May 27, 2021

    @andrewseguin
    Contributor

    Looks like you are missing a mat-sort-header on your headers

  24. Khaaz commented on May 28, 2021

    @Khaaz

    Oh wow, that works thank you so much. I can't believe I missed this I litereally spent 3 hours on this and I couldn't figure it out.
    Thanks a lot! Have a good day!

  25. angular-automatic-lock-bot commented on Jun 28, 2021

    @angular-automatic-lock-bot

    This issue has been automatically locked due to inactivity.
    Please file a new issue if you are encountering a similar or related problem.

    Read more about our automatic conversation locking policy.

    This action has been performed automatically by a bot.

  26. locked and limited conversation to collaborators on Jun 28, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

P4area: material/tabledocs

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions