2017-07-07 61 views
0

私はしばらくの間この壁に頭を打っていましたが、私はついに感じました。私がしようとしているのは、2次元配列に行き、その内容をHTMLのテーブルに出力するテストデータを読み込むことですが、そのデータセットをループするためにngforを使用する方法を理解できませんngForを使用して2次元配列をトラバースする

ここで

私typescriptファイルはここでここで、現時点では

<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> 

を動作しません、私のHTMLは私のconsole.log(this.tableData) enter image description here

から出力される

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) 
     }); 
    } 
} 

です

私の目標は、それがテーブル

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

にこのようにフォーマットしていることが好ましく、私はデータが動的であるため、モデルやインタフェースを使用していたいのですが、それはいつでも変更することができます。誰もがngforを使用して2次元配列をループし、その内容をテーブルに出力する方法を知っていますか?

+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> 
関連する問題