使用Angular 5指令从JSON对象创建动态表

时间:2018-05-08 15:00:40

标签: javascript html angular typescript html-table

是否可以使用Angular 5指令/或借助jQuery创建基于JSON对象的动态表(动态列)?如果是这样的话?

假设我从REST API获得此JSON响应:

{
      name: "Ferrari"
      country: "Italy",
      creater: "Enzo Ferrari"
      cars: [
        {
          modell: "Ferrari 488",
          price: "215.683€"
        },
        {
          modell: "Ferrari Portofino",
          price: "189.704€"
        }
     ]
    }

现在我想从这个数据中创建一个表格,如下所示:

+-----------+----------+--------------+--------------+------------+--------------------+-------------+
| Name      | Country  | Creater      | Modell       | Price      | Modell             | Price       |
+-----------+----------+--------------+--------------+------------+----------------------------------+
|  Ferrari  | Italy    | Enzo Ferrarie| Ferrarie 488 | 189.704€   | Ferrarie Portofino | 189.704€    |
+-----------+----------+--------------+--------------+------------+--------------------+-------------+

解决这个问题的最佳方法是什么?我只是想弄清楚如何解决这个问题?任何帮助都非常感谢。

1 个答案:

答案 0 :(得分:2)

如果表中只有一个对象(表示一个标题行和一个数据行),您可以执行以下操作:

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Country</th>
      <th>Creater</th>
      <ng-template ngFor [ngForOf]="data.cars">
        <th>Modell</th>
        <th>Price</th>
      </ng-template>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>{{ data.name }}</td>
      <td>{{ data.country }}</td>
      <td>{{ data.creater }}</td>
      <ng-template ngFor let-car [ngForOf]="data.cars">
        <th>{{ car.modell }}</th>
        <th>{{ car.price }}</th>
      </ng-template>
    </tr>
  </tbody>

</table>

您可以使用ng-template和ngFor指令循环播放汽车。

重要提示:如果您有多个数据行,则需要确保转换数据,以便始终显示相同数量的列,否则html将被破坏。