1
votes

In the Angular material, MatMenu documentation https://material.angular.io/components/menu/api, the API has a "items" property which is documented like an attribute of type QueryList to the MatMenu component.

In the Angular documentation for QueryList, https://angular.io/api/core/QueryList, the live example shows the @ContentChildren(Item) items: QueryList returns a QueryList of type "Item" component inside the "container" template. And, when I checked out the code for MatMenu directive https://github.com/angular/material2/blob/master/src/lib/menu/menu-directive.ts. They are also getting a list of all the mat-menu-item inside the MatMenu component.

Few questions, I have is:

  • How to use "items" property?
  • Can we dynamically set mat-menu-items using this property?
2

2 Answers

1
votes

You can only access the items property of the menu on an instance of the MatMenu type. In order to get a hold of the menu's reference, you can add a @ViewChild property for it inside your .ts file.

HTML:

<mat-menu #appMenu="matMenu">
    <button mat-menu-item> Settings </button>
    <button mat-menu-item> Help </button>
</mat-menu>
<div>
    <div *ngFor="let item of appMenu.items">
        {{item.getLabel()}}
    </div>
</div>

ts:

export class MyComponent implements OnInit {
    @ViewChild('appMenu') appMenu: MatMenu;
    ngOnInit(): void {
        console.log(this.appMenu.items);
    }
}

Because the QueryList implements an iterable interface, it can be used in both ES6 javascript for (var i of items) loops as well as in Angular templates with *ngFor="let i of menu.items". The documentation states the following about the QueryList

An unmodifiable list of items that Angular keeps up to date when the state of the application changes.

Which leads me to believe that you are not supposed to change the contents of this list dynamically.

0
votes

not sure if I understand your question, probably not but this is what I have in my HTML code:

<mat-menu #appMenu="matMenu">
    <button mat-menu-item *ngIf="(loggedIn)" [routerLink]="['./login']">Login</button>
    <button mat-menu-item *ngIf="(loggedIn)" [routerLink]="['./register']">Register</button>
    <button mat-menu-item *ngIf="(loggedIn)" [routerLink]="['./logout']"> Logout </button>
    <button mat-menu-item *ngIf="(loggedIn)" [routerLink]="['./profile']"> Profile </button>
    <button mat-menu-item *ngIf="(loggedIn)" [routerLink]="['./main']"> Main </button>
</mat-menu>

item is just css, so you can use it to create menu items. It has nothing to do with the content of the item.