在 mat-cell 中使用 ngFor 的正确方法

Sho*_*nha 2 angular-material angular

我想使用 mat-table 在角色列中显示用户的角色名称

用户.ts

export const 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'}]
}];
Run Code Online (Sandbox Code Playgroud)

用户显示.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">{{row.roleName}}
        </mat-cell>
    </ng-container>

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

  </mat-table>
</section>
Run Code Online (Sandbox Code Playgroud)

用户组件.ts

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

export class UserComponent implements OnInit {
    this.displayedColumns = ['firstName', 'lastName', 'roles'];
    this.dataSource.data = this.User;
}
Run Code Online (Sandbox Code Playgroud)

我试图ngFor在 mat-cell 中使用用户,但它抛出错误。我想遍历用户的多个角色并将其显示在列的单行中

nas*_*h11 9

ngFor评论中看到您的解决方案后,事实证明您正在迭代错误的变量。roles没有明确定义,它在你的用户数组中。该row变量一一返回用户数组中的每个对象,因此为了访问roleseach 中的row,您需要遍历row.roles

<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}}  
            <br /> <!-- Use br if you want to display the roles vertically -->
        </ng-container>
    </mat-cell>
</ng-container>
Run Code Online (Sandbox Code Playgroud)