簡體   English   中英

使用* ngFor(Angular 4)循環訪問JSON對象的數組

[英]Loop through array of JSON object with *ngFor (Angular 4)

我想遍歷一個對象數組,這是在我的json文件中。

JSON

[
  {
    "name": "Mike",
    "colors": [
      {"name": "blue"},
      {"name": "white"}
    ]
  },

  {
    "name": "Phoebe",
    "colors": [
      {"name": "red"},
      {"name": "yellow"}
    ]
  }
]

HTML

<div *ngFor="let person of persons">
   <p>{{person.name}}</p> <!-- this works fine-->
   <p *ngFor="let color of person.colors"> <!--I want to list the colors of the person here-->
     {{color.name}}
   </p>
</div>

我無法訪問一個人的顏色數組。 我如何實現這一目標?

我已經查看了這些帖子,但他們的解決方案無法幫助我:

Angular2 ng用於迭代JSON

Angular2 - * ngFor /循環通過帶有數組的json對象

對於角度6.1+,你可以使用默認的管道keyvalue做審查也 ):

<ul>
    <li *ngFor="let recipient of map | keyvalue">
        {{recipient.key}} --> {{recipient.value}}
    </li>
</ul>

工作演示


以前:正如你所說:

Angular2 - * ngFor /循環通過帶有數組的json對象 ,這對你無濟於事

你沒有任何需要,因為你的代碼工作正常,請檢查

工作演示

您的代碼(您顯示的部分)工作正常(請參閱下面鏈接的plunker)。

由於您的問題中沒有顯示的唯一方法是將Javascript對象分配給變量persons ,我建議您向其展示更多代碼/搜索問題。

https://plnkr.co/edit/rj4K2sKHTHsVtdt4OWfC?p=preview

@Component({
  selector: 'my-app',
  template: `
    <div>
      <div *ngFor="let person of persons">
        <p>{{person.name}}</p> <!-- this works fine-->
        <p *ngFor="let color of person.colors"> <!--I want to list the colors of the person here-->
           {{color.name}}
        </p>
      </div>
    </div>
  `,
})
export class App {
  name:string;
  constructor() {

  }

  persons = [
  {
    "name": "Mike",
    "colors": [
      {"name": "blue"},
      {"name": "white"}
    ]
  },

  {
    "name": "Phoebe",
    "colors": [
      {"name": "red"},
      {"name": "yellow"}
    ]
  }
  ];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM