Dynamically table columns and rows [Angular 6 + Bootstrap 3]

Wojciech picture Wojciech · Oct 11, 2018 · Viewed 7.2k times · Source

I need to create tables with dynamically columns and rows. I have an array of objects, which I need to present in table. But table need to be presented in 3 columns. For example:

        var listItems = [
        { name: 'name1', code: 'code1'},
        { name: 'name2', code: 'code2' },
        { name: 'name3', code: 'code3' },
        { name: 'name4', code: 'code4' }
    ];

And table will look sth like:
[name | code] [name | code] [name | code]
name1 code1 name3 code3 name4 code4
name2 code2

What wil be the best solution?

Answer

vignesh nithyanandan picture vignesh nithyanandan · Oct 11, 2018

If items in the array are uniform then you can iterate over the keys.

const list_items = [{name:'abc',code:'123'},{name:'def',code:'456'}];

let keys = Object.keys(list_items[0]); // Get the column names
<table>
  <thead>
    <th *ngFor = 'let key of keys'>{{key}}</th>
  <thead>
  <tbody>
    <tr *ngFor = 'let item of list_items'>
      <td *ngFor = 'let key of keys'>{{item[key]}}</td>
    </tr>
  </tbody>
</table>