0

Currently i have a data table with hard coded column headers and filling in data.. I would like to change this table to make it dynamic so the user can pick the columns to build the table. I would like to know how or in what way i will have to change my json object to ensure dynamic column data table creation.

This is what i have tried but the data is not being loaded.

<table>
  <thead>
    <tr>
      <th *ngFor="let col of columnArray">{{col}}</th>
    </tr>
  </thead>
<table>
<tbody>
   <tr *ngFor="let col of columnArray">
      <td *ngFor="let data of columnData"> {{col.data}} </td>
   </tr>
</tbody>

Currently since my data for the table comes from one object with hard coded headers here is my current working object:

data = [ {'id': 'idValue', 'name': 'nameValue', 'date': 'dateValue', 'description': 'descriptionValue'}, ...
]

but since i don't know what columns the user will pick to create the table it may be columns: id, name, description. Or columns: id, name. I need to have the data flexible so that when the user picks which ever columns to display in a table

1 Answer 1

2

Working format of the data:

columnArray = [ {'header': 'headerValue', 'data': 'dataValue'}, ...
]

Then the template can be:

<table>
    <thead>
       <tr><th *ngFor="let col of columnArray">{{col.header}}></th></tr>
    </thead>
    <tbody>
        <tr>
           <td *ngFor="let col of columnArray"> {{col.data}} </td>
        </tr>
    </tbody>
</table>

If you can provide the data format more apt solution can be provided.

EDIT#1:

Based on your data format, I'd extract keys from an object in your data array for headers.

headers = Object.keys(data[0]);

Then the html should be:

<table>
   <thead>
      <tr><th *ngFor="let col of headers">{{col}}></th></tr>
   </thead>
   <tbody>
      <tr *ngFor="let obj of data">
         <td *ngFor="let col of headers"> {{obj[col]}} </td>
      </tr>
   </tbody>
</table>
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks - i went ahead and updated my post with how my current json looks like - let me know if your answer still applies. I am just having some trouble wrapping my head around the json structure format change.
so based on the json data u have will it be like header: ID, data: { 1, 2, 3,4,5..}... Data: {[header: id, columnData: {1, 2, 3,....}], [header: name, columnData:{sun, moon, stars,....}], ....}
It wouldn't work for multiple rows, please check my updated answer for the data format your provided.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.