Home > database >  Angular Material Menu per mat-row on click to the row
Angular Material Menu per mat-row on click to the row

Time:10-07

I have this Material table:

<table mat-table
       [dataSource]="dataSource">

  <ng-container matColumnDef="id">
    <th mat-header-cell
        *matHeaderCellDef>ID</th>
    <td mat-cell
        *matCellDef="let report"
        [innerText]="report.id"></td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="['id']"></tr>
  <tr mat-row *matRowDef="let row; columns: ['id'];"></tr>

</table>

I'm trying to implement a [matMenuTrigger] for mat-row. Every row will have its own mat-menu with the properties of report.

The problem is I can do

<tr mat-header-row *matHeaderRowDef="['id']" [matMenuTriggerFor]="rowMenu"></tr>

however I do not have a reference to reportMenu since I can only define reportMenu within some matColumnDef:

  <ng-container matColumnDef="id">
    <th mat-header-cell
        *matHeaderCellDef>ID</th>
    <td mat-cell
        *matCellDef="let report"
        [innerText]="report.id"></td>

    <mat-menu #reportMenu="matMenu">
        {{ report.name }}
    </mat-menu>

  </ng-container>

and when I have a reference to mat-row I do not have a reference to the report itself. How do I resolve this?

CodePudding user response:

Get your menu outside of your table. Don't worry, it will work.

Then, follow the documentation to give data to your menu.

<mat-menu #appMenu="matMenu">
  <ng-template matMenuContent let-name="name">
    <button mat-menu-item>Settings</button>
    <button mat-menu-item>Log off {{name}}</button>
  </ng-template>
</mat-menu>

<button mat-icon-button [matMenuTriggerFor]="appMenu" [matMenuTriggerData]="{name: 'Sally'}">
  <mat-icon>more_vert</mat-icon>
</button>

<button mat-icon-button [matMenuTriggerFor]="appMenu" [matMenuTriggerData]="{name: 'Bob'}">
  <mat-icon>more_vert</mat-icon>
</button>

CodePudding user response:

Inside ng-container matColumnDef everything else but mat-cell elements will be ignored. It's by design.

Possibly lazy rendered menu is solution? You can easily pass row data to matMenuContent to render different menu per row.

  • Related