简体   繁体   English

角度2动态列数据表

[英]angular 2 dynamic columns data table

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. 我想知道我将如何或以何种方式更改json对象,以确保创建动态列数据表。

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. 但是由于我不知道用户将选择哪些列来创建表,因此它可能是列:ID,名称,描述。 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 我需要灵活的数据,以便当用户选择要在表中显示的列时

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: 编辑#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: 那么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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM