2017-07-07 174 views
0

我一直在我的頭上靠在這個牆上,但我終於感覺很近了。我想要做的是讀取我的測試數據,它轉到一個二維數組,並將其內容打印到html中的表中,但我無法弄清楚如何使用ngfor循環雖然該數據集使用ngFor來遍歷一個二維數組

這裏是我的打字稿文件

import { Component } from '@angular/core'; 
import { Http } from '@angular/http'; 

@Component({ 
    selector: 'fetchdata', 
    template: require('./fetchdata.component.html') 
}) 
export class FetchDataComponent { 
    public tableData: any[][]; 

    constructor(http: Http) { 

     http.get('/api/SampleData/DatatableData').subscribe(result => { 
      //This is test data only, could dynamically change 
      var arr = [ 
       { ID: 1, Name: "foo", Email: "[email protected]" }, 
       { ID: 2, Name: "bar", Email: "[email protected]" }, 
       { ID: 3, Name: "bar", Email: "[email protected]" } 
      ] 
      var res = arr.map(function (obj) { 
       return Object.keys(obj).map(function (key) { 
        return obj[key]; 
       }); 
      }); 

      this.tableData = res; 
      console.log("Table Data") 
      console.log(this.tableData) 
     }); 
    } 
} 

這裏是我的html不此刻

<p *ngIf="!tableData"><em>Loading...</em></p> 

<table class='table' *ngIf="tableData"> 
    <tbody> 
     <tr *ngFor="let data of tableData; let i = index"> 
      <td> 
      {{ tableData[data][i] }} 
      </td> 

     </tr> 
    </tbody> 
</table> 

在這裏工作是從我console.log(this.tableData) enter image description here

輸出

我的目標是有它的表

1 | foo | [email protected] 
2 | bar | [email protected] 

格式化這樣最好,我想,因爲數據是動態的不使用一個模型或者一個接口,它可以在任何時候改變。有誰知道如何使用ngfor循環遍歷一個二維數組並在表中打印其內容?

+1

您可以簡單地使用內部'* ngFor =「讓數據d」'。 'index'是計數器,並指定循環執行的次數。 –

回答

1

就像Marco Luzzara所說的,你必須使用另一個* ngFor作爲嵌套數組。

我回答這個只是給你一個代碼示例:

<table class='table' *ngIf="tableData"> 
    <tbody> 
     <tr *ngFor="let data of tableData; let i = index"> 
      <td *ngFor="let cell of data"> 
       {{ cell }} 
      </td> 
     </tr> 
    </tbody> 
</table>