如何在Angular2中动态显示键的值?

时间:2018-04-13 09:50:18

标签: angular

我收到这样的JSON响应: -

{
  "status": 1,
  "message": "Data found",
  "list": [
    {
      "id": "1",
      "title": "First Data"
    },
    {
      "id": "2",
      "title": "Second Data"
    }
  ],
  "total": 3,
  "current_page": "1",
  "error": 0
}

在组件文件中,我存储list obj,如下所示: -

viewPage(page,per_page){  
  this._adminPage.fetchAdminPageData(page, per_page).subscribe(
      data => {
            this.list = data.list;
            this.total_item = data.total;
            this.current_page = data.current_page;
            this.arrayOfKeys = Object.keys(this.list[0]);
          },
      err => {
            console.log(err)
          },
      () => {}
    ); 
  this.status = true;       
}

使用this.arrayOfKeys = Object.keys(this.list[0]);我正在获取list的密钥。

在模板页面中,我正在编写以下代码: -

<thead>
  <tr>
     <th *ngFor='let key of arrayOfKeys'>{{key}}</th>
  </tr>
</thead>

这会在表格标题中显示 ID 标题。我这样做是为了使整个表格动态化。

现在,我想通过循环遍历每个对象来列出每行的值。

所以我试着写这样的东西: -

<table class="table table-striped table-bordered responsive">
   <thead>
      <tr>
        <th *ngFor='let key of arrayOfKeys'>{{key}}</th>
      </tr>
   </thead>
   <tbody>
      <tr *ngFor='let items of list'>
        <td *ngFor='let key1 of arrayOfKeys'>[value of that key of that row]</td>
      </tr>
   </tbody>
</table>

{{items.id}}显示id的值,如1,2。我想要{{items.{{key1}}之类的内容来显示每个键的值,例如 1 First Data < / strong>即可。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

您需要使用[]表示法。

<tr *ngFor='let items of list'>
   <td *ngFor='let key1 of arrayOfKeys'>{{ items[key1] }}</td>
</tr>