0

I'm making a dynamic table (from scratch), which build itself from two array of objects, "columns" and "rows".

Each column object have a property, "id", which I want to use in order to select the good property to display on each column (because I don't know the number of columns that will be in the row).

component html:

<table>
    <thead>
        <tr>
            <th *ngFor='let key of columns'>
              {{ key.label }}
            </th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor='let row of rows'>
            <td></td> <!-- I don't know how to do from here -->
        </tr>
    </tbody>
</table>

Sample data:

Columns :

this.columns = [{
        id: "id",
        label: "Id"
      },
      {
        id: "name",
        label: "Name"
      },
      {
        id: "postal_code",
        label: "Postal Code"
      }
    ];

Rows:

this.rows = [{
            id: 120000,
            name: 'Test0',
            postal_code: 44000
          },
          {
            id: 120001,
            useless_column: true,
            postal_code: 44000
          },
          {
            name: 'Test2',
            id: 120002,
            postal_code: 44000
          },
          {
            name: 'Test3',
            id: 120003
          },
        ]

The result should looks something like the following :

|  Id  | Name |Postal Code|
|------|------|-----------|
|120000|Test0 |      44000|
|120001|      |      44000|
|120002|Test2 |      44000|
|120003|Test3 |           |
0

1 Answer 1

3

You will need to loops on columns inside the row loop and then access specific row key something like

<table>
    <thead>
        <tr>
            <th *ngFor='let key of columns'>
              {{ key.label }}
            </th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor='let row of rows'>
            <td *ngFor='let key of columns'>
            {{row[key.id]}}
            </td> 
        </tr>
    </tbody>
</table>

demo

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.