2017-10-05 146 views
0

我有一個json數組,我想打印一個簡單的列表中的值。如何打印值?我必須遵循關鍵值方法嗎?我添加了我的Json數組結構和示例代碼。它向我展示了錯誤。如何在Angular 2中使用* ngFor在列表中打印json數組值?

預期輸出

*456 
*123 

or Arun :123 
test:456 

錯誤:

"'[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays."

JSON數組

{ 
     "records": [{ 
      "arun": [1, 2, 3], 
      "test": [4, 5, 6] 
     }] 
    } 

**myTest.ts** 

export class HomePageComponent extends AppComponent { 

    public bundle: any[]; 

    ngOnInit(){ 
    this.readArray(); 
    } 

    readArray() { 
    this.bundle = { 
     "records": [{ 
      "arun": [1, 2, 3], 
      "test": [4, 5, 6] 
     }] 
    } 
    console.log("array",this.bundle); 
    } 

testComponent.html

<ul *ngFor="let det of bundle;"> 
    <li>{{det.records}}</li> 
</ul> 

回答

1

您需要使用ngFor一個數組,它應該是<div *ngFor="let record of bundle.records">,你也有一個嵌套的數組,你可以使用 Object.keys作爲訪問項目在演示中

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div *ngFor="let record of bundle.records"> 
     <ul *ngFor="let key of objectKeys(record)"> 
     <li>{{key}} :: {{record[key]}}</li> 
     </ul> 
    </div> 
    `, 
}) 

DEMO

+0

有沒有什麼辦法可以把它放在一個函數中,並使console.log知道這些值以及它是如何打印的..我想我的輸出是456 !!!怎麼做@ Sajeetharan –

+0

@DeepakVijay檢查這個演示https://plnkr.co/edit/2lyNFqkKFoFVbU5nXWgq?p=preview – Sajeetharan

0

讓Object.keys在模板中可訪問並在* ngFor中使用它。

export class HomePageComponent extends AppComponent { 
    objectKeys = Object.keys; 

然後在模板

<ul *ngFor="let key of objectKeys(bundle.records[0]);"> 
    <li>{{key + ' : ' + bundle.records[0][key]}}</li> 
    </ul>