【问题标题】:angular 2 dynamic columns data tableangular 2动态列数据表
【发布时间】:2018-12-18 13:38:31
【问题描述】:

目前我有一个带有硬编码列标题并填写数据的数据表。我想更改此表以使其动态化,以便用户可以选择列来构建表。我想知道如何或以何种方式更改我的 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。我需要使数据灵活,以便当用户选择要在表格中显示的列时

【问题讨论】:

    标签: json angular


    【解决方案1】:

    数据的工作格式:

    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>
    

    【讨论】:

    • 谢谢 - 我继续更新我的帖子,用我当前的 json 的样子 - 如果你的答案仍然适用,请告诉我。我只是在理解 json 结构格式更改时遇到了一些麻烦。
    • 所以根据你拥有的 json 数据,它会不会像 header: ID, data: { 1, 2, 3,4,5..}... Data: {[header: id, columnData: {1, 2, 3,....}], [header: name, columnData:{sun, moon, stars,....}], ....}
    • 它不适用于多行,请查看我的更新答案以了解您提供的数据格式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-05
    • 1970-01-01
    • 2018-10-03
    • 2018-02-18
    • 2018-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多