0
votes

I'm trying to use a mat-selection-list as an option in a mat-menu:

export class AppComponent implements OnInit() {
   items: string[] = ['item1', 'item2', 'item3']
   constructor(){}
}
<button [matMenuTriggerFor]="settings">
<\button>

<mat-menu #settings="matMenu">
   <button mat-menu-item [matMenuTriggerFor]="items">Items<\button>
<\mat-menu>

<mat-menu #items="matMenu">
   <mat-selection-list>
      <mat-list-option *ngFor="let item of items" [value]="item">
         {{item}}
      <\mat-list-option>
   <\mat-selection-list>
<\mat-menu>

When I click the button, the menu appears, in which the element "Items" can be chosen. In "Items", I'm expecting to see a list of the items item1, item2 and item3. However, nothing is displayed and the following error is thrown:

Error: Cannot find a differ supporting object [object Object] of type 'object'. NgFor only supports binding to Iterables such as Arrays.

How is my array items not suitable for ngFor? What am I missing? The list is populated correctly if I add each mat-list-option manually, but with ngFor it's causing me problems.

1

1 Answers

1
votes

I see two possible issues:

1. Your use of #settings="matMenu" and #items="matMenu" sets the value of both settings and items to the same reference of matMenu, which is probably not what you want. From the docs:

How Angular assigns values to template variables
...
If the variable specifies a name on the right-hand side, such as #var="ngModel", the variable refers to the directive or component on the element with a matching exportAs name.

https://angular.io/guide/template-reference-variables#how-angular-assigns-values-to-template-variables

You should just use #settings and #items. However...

2. #items in your template will override the items: string[] in your component. Pick a different variable name for your <mat-menu> element -- maybe #itemsMenu, for example.