簡體   English   中英

使用 mat-table 在不同行中顯示用戶的多個角色

[英]Display multiple roles of a user in different rows using mat-table

我想在角色列中顯示用戶的多個角色名稱,但使用 mat-table 在不同的行中

我正在發出 API GET 請求以顯示用戶和角色。 這是返回的樣本 JSON。

[{
    firstName: 'User',
    lastName: '1',
    roles: [
        {id: '1', roleName: 'first Role'},
        {id: '2', roleName: 'second Role'}
        ]
}, {
    firstName: 'User',
    lastName: '2',
    roles: [
        {id: '1', roleName: 'third Role'},
        {id: '2', roleName: 'fourth Role'}
        ]
}];

用戶顯示器.html

<section>
  <mat-table class="matTable" [dataSource]="dataSource">
    <ng-container matColumnDef="firstName">
      <mat-header-cell *matHeaderCellDef> First Name </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.firstName}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="lastName">
      <mat-header-cell *matHeaderCellDef> Last Name </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.lastName}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="roles">
      <mat-header-cell *matHeaderCellDef> Roles </mat-header-cell>
      <mat-cell *matCellDef="let row">        
        <ng-container *ngFor="let role of row.roles">
            {{role.roleName}}  
        </ng-container>
        </mat-cell>
    </ng-container>

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

  </mat-table>
</section>

用戶.component.ts

import { MatTableDataSource } from '@angular/material';

export class UserComponent implements OnInit {
    this.displayedColumns = ['firstName', 'lastName', 'roles'];
    this.dataSource.data = this.User;
}

我試圖在 mat-cell 內使用 ngFor,但它的拋出錯誤。 我想遍歷用戶的多個角色並將其分別顯示在不同的行中。 例如

角色
用戶 1 第一個角色
用戶 1 第二個角色
用戶 2 第三個角色
用戶 2 第四個角色

您需要以您希望在屏幕上看到的格式提供數據。

因此,創建一個 object 列表,該列表已經具有{ roleName: 'first Role', firstName: 'User', lastName: '1'}

我們正在使用flatMap帶出嵌套數組並創建一個新的 object,而不是編輯現有的 object。 也可以使用Object.assign

 let User = [{ firstName: 'User', lastName: '1', roles: [{ id: '1', roleName: 'first Role' }, { id: '2', roleName: 'second Role' } ] }, { firstName: 'User', lastName: '2', roles: [{ id: '1', roleName: 'third Role' }, { id: '2', roleName: 'fourth Role' } ] }]; let UserList = User.flatMap(p => p.roles.map(r => ({ firstName: p.firstName, lastName: p.lastName, role: r.roleName }))) console.log(UserList)

現在您可以直接將列放在這里:

   <ng-container matColumnDef="role">
  <mat-header-cell *matHeaderCellDef> Role Name </mat-header-cell>
  <mat-cell *matCellDef="let row"> {{row.role}} </mat-cell>
</ng-container>

暫無
暫無

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

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