Reputation: 125
How do I create a table with dynamic columns and rows in angular2
I have the data coming from a rest service and captured in this observable
this._physicalDataService.getPhysicalData().subscribe(res=> this.data = res)
I can display the rows dynamically through this code. How do I make the columns and the column headers dynamic too ie how can i extract all the JSON keys in an array to put another loop on top.
To clarify my backend service may return different datasets with different columns and row and I want to show them dynamically on a page.
<thead class="no-bd">
<tr>
<th>Id</th>
<th>Number</th>
<th >Employee Name</th>
<th >Manager Name</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let tablerows of data">
<td>
{{tablerows.row_id}}
</td>
<td>{{tablerows.number}}</td>
<td >{{tablerows.employee_name}}</td>
<td >{{tablerows.manager_name}}
</td>
</tr>
Upvotes: 1
Views: 7292
Reputation: 13805
You can use same *ngFor on your <th></th>
too.
But For that you will need to calculate length of Object.It Will give you no of elements in each Array.
var custObject = new Object();
myArray["firstname"] = "Gareth";
myArray["lastname"] = "Simpson";
myArray["age"] = 21;
this.objLength = Object.keys(myArray).length; // Calc length of Object i.e. 3
After You Have length of Object , You can render your <th>
block that many times using below pipe:
<th *ngFor='#key of 5 | demoNumber;let i=index'>
Column{{i}}
</th>
Pipe:
import {Pipe, PipeTransform} from 'angular2/core';
@Pipe({name: 'demoNumber'})
export class DemoNumber implements PipeTransform {
transform(value, args:string[]) : any {
let res = [];
for (let i = 0; i < value; i++) {
res.push(i);
}
return res;
}
}
This will calculate no of Object fields & then ngFor will render Coulmn+index for each field.
Hope this helps.
Upvotes: 1