首页 > 解决方案 > angular 2动态列数据表

问题描述

目前我有一个带有硬编码列标题并填写数据的数据表。我想更改此表以使其动态化,以便用户可以选择列来构建表。我想知道如何或以何种方式更改我的 json 对象以确保创建动态列数据表。

这是我尝试过的,但没有加载数据。

<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>

目前,由于我的表格数据来自一个带有硬编码标题的对象,因此这是我当前的工作对象:

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

但由于我不知道用户将选择哪些列来创建表,所以它可能是列:id、name、description。或列:id、name。我需要使数据灵活,以便当用户选择要在表中显示的列时

标签: jsonangular

解决方案


数据的工作格式:

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

那么模板可以是:

<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>

如果您可以提供数据格式,则可以提供更合适的解决方案。

编辑#1:

根据您的数据格式,我将从您的数据数组中的对象中提取键作为标题。

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

那么html应该是:

<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>

推荐阅读