具有嵌套数据源的 Angular Material 表

2024-01-12

我在中显示 JSON 文件的数据mat-table. The mat-table显示行效果很好,但我必须连续显示数组内的数据。但是,我不知道最好使用什么谓词。我尝试了 where 谓词但它不起作用。

Data:

{
  "fname": "Mark",
  "lname": "jhony",
  "parcels": [
    {
      "parcelId": 123,
      "parcelName: "asd",
      "parcelItems": [
        { 
          "itemId": 2,
          "itemName": "perfume"
        },
        { 
          "itemId": 4,
          "itemName": "soap"
        }
      ]
    },
    {
      "parcelId": 144,
      "parcelName": "parcel2",
      "parcelItems": [
        { 
          "itemId": 2,
          "itemName": "headphones"
        },
        { 
          "itemId": 4,
          "itemName": "mouse"
        }
      ]
    }
  ]
}

HTML 模板:

<table mat-table [dataSource]="dataSource" matSort>
  <ng-container matColumnDef="fname">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Fname </th>
    <td mat-cell *matCellDef="let element"> {{element.fname}} </td>
  </ng-container>
  <ng-container matColumnDef="lname">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Lname </th>
    <td mat-cell *matCellDef="let row"> {{row.lname}} </td>
  </ng-container>
  <ng-container matColumnDef="parcelid">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Parcelid </th>
    <td mat-cell *matCellDef="let element"> {{element.parcels[0].parcelId}} </td>

  </ng-container>
  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row;columns: displayedColumns;"></tr>
</table>

在这里我可以访问parcelId,如上element.parcels[0].parcelId。但是,我想让它重复,这样fname, lname并且可以在表格中看到某个用户的所有包裹


如果你事先知道地块的数量,而且是一个固定的数字,你可以在HTML模板中使用ngFor,在获取数据时使用for循环,在设置数据源之前,填写正确的显示列数和名称。如果您没有此信息,您始终可以单独在模板中使用 ngFor,列出单元格中的所有数据,如下所示:https://stackblitz.com/edit/nested-table-data https://stackblitz.com/edit/nested-table-data

<ng-container matColumnDef="parcels">
    <mat-header-cell *matHeaderCellDef> Parcels </mat-header-cell>
    <mat-cell *matCellDef="let element">
        <div class="parcels">
            <ng-container *ngFor="let parcel of element.parcels">
                <div class="parcel">
                    <ul>
                        <li>ID: {{parcel.parcelId}}</li>
                        <li>Name: {{parcel.parcelName}}</li>
                    </ul>
                    <ul>
                        <li *ngFor="let item of parcel.parcelItems">
                            <span>{{item.itemId}}: {{item.itemName}}</span>
                        </li>
                    </ul>
                </div>
            </ng-container>
        </div>
    </mat-cell>
</ng-container>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

具有嵌套数据源的 Angular Material 表 的相关文章

随机推荐