Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to use ngFor inside mat-cell

I want to display the roleName of User in Roles column using 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;
}

I tried to user ngFor inside mat-cell but its throwing error. I want to iterate over multiple roles of user and display it inside a single row in the column

like image 654
Shorya Sinha Avatar asked Oct 30 '25 01:10

Shorya Sinha


1 Answers

After seeing your ngFor solution in the comments, it turns out you're iterating over the wrong variable. roles is not defined explicitly, it is within your user array. The row variable returns each object in the user array one by one so in order to access the roles in each row, you need to iterate over 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>
like image 153
nash11 Avatar answered Oct 31 '25 22:10

nash11



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!