在Mat-Cell内部使用ngFor的正确方法

时间:2019-11-03 19:56:52

标签: angular angular-material

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

User.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'}]
}];

UserDisplay.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>

user.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 个答案:

答案 0 :(得分:1)

在评论中看到您的ngFor解决方案后,事实证明您正在遍历错误的变量。 roles未明确定义,它在您的用户数组内。 row变量一个接一个地返回用户数组中的每个对象,因此,要访问每个roles中的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>