I'm looking for a way to add columns to a ngx-datatable "dynamically" but I am not able to find a way. What I am trying to accomplish is some sort of calendar. To keep it simple let's say I've got some objects I want to show in the 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 handling objects. I would love to use it like in this example: https://github.com/swimlane/ngx-datatable/blob/master/demo/basic/inline.component.ts
The syntax there 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>
Thanks!
I wanted to answer this question even though it was posted over a year ago because I think it will help others that are trying to accomplish the same thing. I'm using Angular6 with Typescript but you should still be able to apply the solution to your needs.
First I added a resultColumns: any[] = [];
declaration in my class. On 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'm calling a function I made called generateColumns()
which will be responsible for populating the resultColumns
object.
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
});
}
Assuming that you get your rows from somewhere:
this.someService.getRows(someParam).subscribe(rows => {
if (rows?.length > 0) {
this.columns = Object.keys(rows[0]);
}
this.rows = rows;
}, (error: MysqlError) => {
this.error = error;
}));
Then in your template:
<ngx-datatable
...
[rows]="rows"
>
<ngx-datatable-column *ngFor="let col of columns" [prop]="col"></ngx-datatable-column>
</ngx-datatable>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With