3

Seems to be the same requirement like AngularJS "Vertical" ng-repeat but solution doesn't work for *ngFor

I have this object array that I am trying to bind to an HTML table. Its format is something like below:

[
 {
   "Animal":"Dog",
   "Country":"France",
   "Food":"Tofu",
   "Car":"Nano",
   "Language":"TypeScript"
 }
]

Now this can simply be formatted in the default HTML horizontal table way like this:

<table>
  <tr>
    <th>Animal</th>
    <th>Country</th>
    <th>Food</th>
    <th>Car</th>
    <th>Language</th>
  </tr>
  <tr *ngFor="let data of datas">
    <td>{{data.Animal}}</td>
    <td>{{data.Country}}</td>
    <td>{{data.Food}}</td>
    <td>{{data.Car}}</td>
    <td>{{data.Language}}</td>
  </tr>
</table>

This would create table like below(Please ignore the data in the table;its just to give an idea.):

[1]: https://i.stack.imgur.com/VG

But how would I create a structure like this with dynamic data(kind of a vertical table): enter image description here

Aakash Thakur
  • 3,837
  • 10
  • 33
  • 64

2 Answers2

5

In Component:

this.arrayOfKeys = Object.keys(this.datas[0]);

html:

<table>
    <tr *ngFor="let key of arrayOfKeys">
        <th>{{key}}</th>
        <td *ngFor="let data of datas">
            {{data[key]}}
        </td>
    </tr>
</table>
Ido Ganzer
  • 88
  • 8
0

Use ng-container if You have data structure similar to groups[].items[].name

So, if You want to add row

<table>
    <ng-container *ngFor="let group of groups">
        <tr>
            <td>{{group.name}}</td>
        </tr>
        <tr *ngFor="let item of group.items">
            <td>{{item.name}}</td>
        </tr>
    </ng-container>
</table>

Source: https://stackoverflow.com/a/44086855/1840185

Shaishav Jogani
  • 2,111
  • 3
  • 23
  • 33
Viktor Reinok
  • 113
  • 13
  • Consider my scenario, I have 2 lists coming from the service call, one list will be used as the table headings and another list will be used as the table data. Something like this--- List 1 - {Name, Age} List 2 - {Shubham, 25} Table should look like - Name Shubham Age 25 Can anyone help? – Shubham Arya Nov 18 '19 at 07:24
  • So, You have a list that describes structure and another list that contains data. I would create a list `schema[].names[]` inside for loops above the example provided above. – Viktor Reinok Nov 18 '19 at 10:10
  • Sure, please create minimal example that represents your problem I am willing to look into that. – Viktor Reinok Nov 18 '19 at 14:39
  • Hi Viktor, Got it to work. Thanks a lot though :):):) – Shubham Arya Nov 19 '19 at 06:37