使用循环显示数组的对象

时间:2019-01-07 10:34:06

标签: angular typescript angular6

我有一个名为addresses的数组,其中包含多个对象(即多个地址)。

[
 {
   "name": "Jhon Doe",
   "gender": "Male",
   "addresses": [
        {
            "addressType": "Home",
            "city": "Portland",
            "country": "United States",
            "postalCode": "97286",
            "state": "Oregon",
            "street": "86807 Twin Pines Way"
        },
        {
            "addressType": "Office",
            "city": "Phoenix",
            "country": "United States",
            "postalCode": "85083",
            "state": "Arizona",
            "street": "0583 Dayton Junction"
        }
    ]
 },
  .
  .
  .
  .
  .
  .
  .
  .
 {
   "name": "Mark Wood",
   "gender": "Male",
   "addresses": [
      {
         "addressType": "Home",
          "city": "Minneapolis",
          "country": "United States",
          "postalCode": "55417",
          "state": "Minnesota",
          "street": "0 School Way"
      },
      {
          "addressType": "Office",
          "city": "Tuscaloosa",
          "country": "United States",
          "postalCode": "35487",
          "state": "Alabama",
           "street": "98 Vernon Place"
      },
      {
          "addressType": "Others",
           "city": "Sacramento",
           "country": "United States",
           "postalCode": "95833",
           "state": "California",
           "street": "40581 Superior Pass"
         }
      ]
    }

  ]

参考图片

enter image description here

我要显示所有地址,具体取决于存在的对象数(即地址的编号/类型)。

  

我可以使用对象索引位置显示多个地址,但是我想通过循环显示。

Stackblitz DEMO

3 个答案:

答案 0 :(得分:2)

您可以循环访问地址:

<td *ngFor="let abc of contact.addresses">
    {{abc.addressType}} 
</td>

答案 1 :(得分:1)

<div class="cust-detail" *ngFor="let contact of contacts">
    <tr>
      <td>Name</td>
      <td>{{contact.name }}</td>
    </tr>
    <tr>
      <td>Gender</td>
      <td>{{contact.gender}} </td>
    </tr>
    <tr>
      <td>Address</td>
      <td>
        <div *ngFor="let addr of contact.addresses">
            {{addr.street}},
            {{addr.city}},
            {{addr.country}},
            {{addr.state}},
            {{addr.postalCode}} ({{addr.addressType}})
        </div>
      </td>
    </tr>
    <hr>
</div>

答案 2 :(得分:1)

尝试一下,这就像直接索引所需的结构一样:

<tr *ngFor="let eachAddress of contact?.addresses;let i = index">
  <ng-container *ngIf="i === 0; else notFirst"><td>Address</td></ng-container>
  <ng-template #notFirst><td></td></ng-template>
  <td>{{eachAddress?.street}},
      {{eachAddress?.city}},
      {{eachAddress?.country}},
      {{eachAddress?.state}},
      {{eachAddress?.postalCode}} ({{eachAddress?.addressType}})
  </td>
</tr>

https://stackblitz.com/edit/angular-movie-read-load-json-sample-eg-dmhidj?file=src/app/app.component.html