Ngx-datatable multiple columns from model
I'm looking for a way to add columns to ngx-datatable "dynamically" but I can't find a way. What I am trying to do is some kind of calendar. For simplicity's sake, let's say I have some objects that I want to show in a table, for example:
rows: [
{ name: Joe, availableDays: [ { date:'01-01-2017', foo: true }, { date:'03-01-2017', foo: true }]}
{ name: Jack, availableDays: [ { date:'01-04-2017', foo: true }]}
]
Now I would like to see the following columns and values:
Name; 01-01-2017; 02-01-2017; 03-01-2017; 04-01-2017
Joe; true; false; true; false
Jack; false; false; false; true
Ignore 'Foo'. I just added it to show that I am looking for something to handle objects. I would like to use it like in this example: https://github.com/swimlane/ngx-datatable/blob/master/demo/basic/inline.component.ts
The syntax is like this:
<ngx-datatable-column name="Name">
<ng-template ngx-datatable-cell-template let-value="value" let-row="row">
[...]
</ng-template>
</ngx-datatable-column>
Thank!
source to share
I wanted to answer this question even though it was posted over a year ago because I think it will help others who are trying to achieve the same. I am using Angular6 with Typescript, but you can still apply the solution for your needs.
First, I added a declaration resultColumns: any[] = [];
to my class. From the HTML side, I added this bit:
<ngx-datatable class='material'
[rows]='row'
[columnMode]='"flex"'
[headerHeight]='50'
[footerHeight]='50'
[rowHeight]='"auto"'
[limit]='20'
[messages]='messageObject'
[sortType]='"single"'
[loadingIndicator]='loading'
[scrollbarH]="true">
<ngx-datatable-column *ngFor="let col of resultColumns; let i = index" [name]="col.name" [flexGrow]="col.flexGrow">
<ng-template ngx-datatable-header-template>
{{ col.name }}
</ng-template>
<ng-template let-value="value" ngx-datatable-cell-template>
{{ value }}
</ng-template>
</ngx-datatable-column>
</ngx-datatable>
In my ngOnInit, I call a function I created with a name generateColumns()
that will be responsible for populating the object resultColumns
.
generateColumns(rows) {
this.rows.forEach((item) => {
this.resultColumns.push({
name: item.date,
prop: item.foo,
flexGrow: 1.0,
minWidth: 100
});
}
// Pushes the name column to the front of the column list
this.resultColumns.unshift({
name: 'Name',
prop: item.name,
flexGrow: 1.0,
minWidth: 100
});
}
source to share