Twitter LogoFacebook Logo
Angular Material UI: Menu
Hello, in this tutorial, I will be talking Menus in Angular material.
By: King Wai Mark

The menu is a responsive floating panel that contains responsive elements that we can attach to an element.

We can put it above, below, or on top of the element.

Image from Codeible.com

We can also include menus inside another menu as much as we want.

Image from Codeible.com

To begin, add the MatMenuModule to the project. Go to the app component TypeScript file, add the import statement, and add it to the app.

...
import { MatMenuModule } from '@angular/material/menu';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    ...
    MatMenuModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Creating the Menu

To create the menu, use the mat-menu element Go into a HTML file and add it to the page.

<mat-menu>


</mat-menu>

Then to the add menu items, add a button element for each item and then apply the mat-menu-item property to each button.

<mat-menu>

   <button mat-menu-item>Item 1</button>
   <button mat-menu-item>Item 2</button>
   <button mat-menu-item>Item 3</button>
</mat-menu>

Lastly, give the menu a template reference.

<mat-menu #mainMenu>

   <button mat-menu-item>Item 1</button>
   <button mat-menu-item>Item 2</button>
   <button mat-menu-item>Item 3</button>
</mat-menu>

The mat-menu element does not render by itself. If we launch our application, nothing will show. It must be triggered by something.

To trigger it, we need to have a visible element in our page. Then apply the [matMenuTriggerFor] attribute to it and pass in the reference for the menu we want to trigger.

<button [matMenuTriggerFor]="mainMenu">Menu Example Trigger</button>

Nested Menus

To add a menu inside another menu, we repeat the steps from before.

Create another mat-menu component and then apply the [matMenuTriggerFor] attribute to the item in the previous menu that we want to use to trigger the new menu.

<mat-menu #subMenu>

   <button mat-menu-item>Submenu 1</button>
   <button mat-menu-item>Submenu 2</button>
   <button mat-menu-item>Submenu 3<</button>
</mat-menu>

<mat-menu #mainMenu>

   <button mat-menu-item [matMenuTriggerFor]="subMenu">Item 1</button>
   <button mat-menu-item>Item 2</button>
   <button mat-menu-item>Item 3</button>
</mat-menu>

Positioning the Menu

By default, the menu is displayed underneath the element that is triggering it. This behavior can be modified.

For example, if we want it to overlap the element, apply the overlapTrigger property to the menu.

<mat-menu #mainMenu overlapTrigger>

  ...
</mat-menu>

To place the menu above the element, apply the yPosition attribute to the menu and set it to above. 

<mat-menu #mainMenu yPosition="above">

  ...
</mat-menu>

Lastly, to place the menu at the end of the element, we use xPosition and set it to before. 

<mat-menu #mainMenu xPosition="before">

  ...
</mat-menu>


Sign In