Reputation: 967
I'm working on Angular 5. Quite new to this so I'm not sure if it's already there or not.
In my component.ts, I have got a stream response$. The data in there is an array. Each element in the array is unknown. So data can be [ { id: 1, name: 'test'}, { id: 2, name: 'test2'} ] or [ { label: 'abc', desc: 'abc'}, { label: 'def', desc: 'def'} ]
So I only know it's an array. How can I display this data structure as a table in Angular? Can someone shed some ideas how to start?
Upvotes: 0
Views: 368
Reputation: 967
I came up with a solution. First, create an Angular Pipe to extract keys from a map. Then we loop through the array with ngFor and use the key.
<table>
<tr *ngFor="let row of data | async">
<td *ngFor="let key of row | mapKeys">{{row[key]}}</td>
</tr>
</table>
So the newly created pipe is named mapKeys. Here is the code
import { Pipe, PipeTransform } from '@angular/core';
import _ from 'lodash';
@Pipe({name: 'mapKeys'})
export class MapKeysPipe implements PipeTransform {
transform(map: Map<any, any>): Array<any> {
let res = [];
_.forEach(map, (val, key) => {
res.push(key);
});
return res;
}
}
Upvotes: 0
Reputation: 2590
If your objects always identical to each we ca do something like this:
First Read unique keys:
//identify unique keys in the array
for (var key in this.arr1[0]) {
if (this.arr1[0].hasOwnProperty(key)) {
this.columnsArr.push(key);
}
}
Then iterate like this:
<table style="width:100%">
<tr>
<th *ngFor="let header of columnsArr">{{header}}</th>
</tr>
<tr *ngFor="let data of arr1">
<td>{{data[columnsArr[0]]}}</td>
<td>{{data[columnsArr[1]]}}</td>
</tr>
</table>
Here is the working stackblitz You can replace arr1 and check the outcome.
Upvotes: 1