JL Gradley
JL Gradley

Reputation: 2031

Angular: Dynamically updating mat-menu-item(s) does not update the view

I have a material menu (mat-menu) triggered from a history icon button that should contain a running list of accounts the user has searched for.

In the class:

searchHistoryList: Array<string>; // populated dynamically while the app is in use

In the View:

<button mat-icon-button [matMenuTriggerFor]="accountHistoryList">
    <mat-icon>history</mat-icon>
</button>

<mat-menu #accountHistoryList="matMenu">
    <button mat-menu-item *ngFor="let acc of searchHistoryList">
      <button mat-menu-item (click)="loadCustomer(acc)">{{acc}}</button>
    </button>
</mat-menu>

The issue is that this list of mat-menu-item(s) seems to only render once. Just experimenting I found that if I initialize the the searchHistoryList array that's bound to this template with some hardcoded values, they show up in the menu item list. However, if I programmatically add values to the searchHistoryList array at runtime, those do not display.

What am I doing something wrong?

Upvotes: 0

Views: 2537

Answers (1)

Eldar
Eldar

Reputation: 10790

You need to use trackByFn inorder to tell angular that your collection has changed and a re-render is needed.

<mat-menu #accountHistoryList="matMenu">
    <button mat-menu-item *ngFor="let acc of searchHistoryList;trackBy=trackByMethod">
      <button mat-menu-item (click)="loadCustomer(acc)">{{acc}}</button>
    </button>
</mat-menu>

Function Definition :

trackByMethod(index:number, el:any): number {
    return el.id;
  }

Upvotes: 1

Related Questions