簡體   English   中英

ngFor 在 angular 與數組數組

[英]ngFor in angular with array of array

  1. 項目清單:
jsonObject = [
    {
      place: 'place1',
      fatherDetails: [
        {name: 'place1_father1', adharId: 134567},
        {name: 'place1_father2', adharId: 124567},
      ],
      motherDetails: [
        {name: 'place1_mother1', adharId: 123456},
        {name: 'place1_mother2', adharId: 123457},
        {name: 'place1_mother3', adharId: 123467},
      ],
    },
    {
      place: 'place2',
      fatherDetails: [
        {name: 'place2_father1', adharId: 123567},
        {name: 'place2_father2', adharId: 12567},
      ],
      motherDetails: [
        {name: 'place2_mother1', adharId: 1234567},
        {name: 'place2_mother2', adharId: 1234567},
        {name: 'place2_mother3', adharId: 1234567},
      ],
    }
  ];

如何使用ngFor循環HTML中的所有fatherDetails對象? 基本上,我需要這樣的東西:

<mat-option *ngFor = "let father of jsonObject">
   {{father.name}}
</mat-option>

但是,這行不通。 因為,它必須循環兩次。

注意您需要迭代第一個循環,第二個循環將在第一個循環的 object 數組中進行迭代。

 jsonObject = [{ place: 'place1', fatherDetails: [{ name: 'place1_father1', adharId: 134567 }, { name: 'place1_father2', adharId: 124567 }, ], motherDetails: [{ name: 'place1_mother1', adharId: 123456 }, { name: 'place1_mother2', adharId: 123457 }, { name: 'place1_mother3', adharId: 123467 }, ], }, { place: 'place2', fatherDetails: [{ name: 'place2_father1', adharId: 123567 }, { name: 'place2_father2', adharId: 12567 }, ], motherDetails: [{ name: 'place2_mother1', adharId: 1234567 }, { name: 'place2_mother2', adharId: 1234567 }, { name: 'place2_mother3', adharId: 1234567 }, ], } ];
 <tr *ngFor="let object of jsonObject;let i = index;"> <td>{{i}}</td> <td * ngFor="let o of object.motherDetails">{{o}}</td> </tr>

只需從所有項目中提取fatherDetails,平面數組並對其進行迭代

在組件 class 中:

 this.allfathersDetails = this.jsonObject.map( item => item.fatherDetails).flat();

在模板中:

 <div *ngFor="let details of allfathersDetails">
 ...

你可以試試這段代碼。

<div *ngFor = "let object of jsonObject">
<div *ngFor ="let father of object.fatherDetails>
<span>{{father.name}}</span>
</div>
</div>

這可以使用 Angular 的 ng-container 輕松實現。

    <ng-container *ngFor="let object of jsonObject>
        <mat-option *ngFor = "let father of object.fatherDetails">
            {{father.name}}
        </mat-option>
    </ng-container

ng-container 不會用不必要的 div 使您的 DOM 混亂,並允許您訪問該嵌套數組。

暫無
暫無

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

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