Правильный способ использования ngFor внутри mat-cell - PullRequest
1 голос
/ 03 ноября 2019

Я хочу отобразить roleName пользователя в столбце Roles с использованием таблицы mat

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;
}

Я пытался использовать ngFor внутри mat-cell, но его ошибка броска. Я хочу перебрать несколько ролей пользователя и отобразить их в одной строке в столбце

1 Ответ

0 голосов
/ 04 ноября 2019

После просмотра вашего 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>
.
...