0

https://stackblitz.com/edit/dynamic-columns-mat-table

This is what i have so far.

This table renders perfectly but my requirement is that i dont know the column names beforehand so i need to mention the column name like this for example

Instead of ${element.description} => ${element.elementname}

OR

${element.description} => ${element.'description'}

Any suggestions would be appreciated. Thank you.

HTML

  <mat-table #table [dataSource]="dataSource">
      <ng-container *ngFor="let column of columns" [cdkColumnDef]="column.columnDef">
          <mat-header-cell *cdkHeaderCellDef>{{ column.header }}</mat-header-cell>
             <mat-cell *cdkCellDef="let row">{{ column.cell(row) }}</mat-cell>
      </ng-container>
 <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
 <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>

Component.ts

export class DataPageComponent implements OnInit,AfterViewInit {

 columns = [
  { columnDef: 'Gender', header: 'Gender',    cell: (element: any) => `${element.Gender}` },
  { columnDef: 'VechiclesOwned', header: 'Vechicles Owned',    cell: (element: any) => `${element.VechiclesOwned}` },
  { columnDef: 'description', header: 'description',    cell: (element: any) => `${element.description}` },
  ];


  displayedColumns = this.columns.map(c => c.columnDef);

  dataSource = new FormDataSource(this.af);

   constructor(public af: AngularFireDatabase) { }
}


 export class FormDataSource extends DataSource<any>{

constructor(private af: AngularFireDatabase){
  super()
  }

   connect():Observable<any[]>{

   return  this.af.list('/data');

   }

 disconnect() {}

}
DEV
  • 949
  • 1
  • 9
  • 29

1 Answers1

0

Sorry I don't have the clout to simply comment yet, but it seems that Material is not the problem here (thank goodness). Although it would help if you made a plunkr about what you are doing or trying to do. I've solved my own problems that way actually :-) Here is one I made for you real quick. Sorry I'm using bootstrap instead of Material

If you just use an array in angular, you should be able to refer to them in your HTML like this:

html:

<table>
<thead>
<th *ngFor="let data in array">{{data}}</th>
</thead>
</table>
BSchnitzel
  • 136
  • 2
  • 15
  • Hmm, cool. Just noticed last week it seems stackblitz is becoming the newer thing for Angular here. I'll check it out today using Material actually since I need the practice :-) – BSchnitzel Mar 12 '18 at 13:06