Angular Material - Menu



The <mat-menu>, an Angular Directive, is used to create a menu and attach it with a control with material design styling and animation capabilities.

In this chapter, we will showcase the configuration required to draw a menu control using Angular Material.

Create Angular Application

Follow the following steps to update the Angular application we created in Angular Material - First Application chapter −

Step Description
1 Create a project with a name material-app as explained in the Angular Material - First Application chapter.
2 Modify app.ts and app.html as explained below. Keep rest of the files unchanged.
3 Compile and run the application to verify the result of the implemented logic.

app.ts

Following is the content of the modified app.ts.

import { Component, signal } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatMenuModule } from '@angular/material/menu';

@Component({
   selector: 'app-root',
   imports: [
      FormsModule,
      MatFormFieldModule,
      MatMenuModule, 
      MatButtonModule, 
      MatCheckboxModule,
      ReactiveFormsModule,
   ],
   templateUrl: './app.html',
   styleUrl: './app.css'
})
export class App {
   protected readonly title = signal('material-app');
   disabled = false;
   checked = false;
}

app.html

Following is the content of the modified HTML host file app.html.

<button mat-button [matMenuTriggerFor] = "menu">File</button>
<mat-menu #menu = "matMenu">
   <button mat-menu-item>New</button>
   <button mat-menu-item>Open</button>
   <button mat-menu-item [matMenuTriggerFor] = "recent">Recent</button>
</mat-menu>
<mat-menu #recent = "matMenu">
   <button mat-menu-item>File 1</button>
   <button mat-menu-item>File 2</button>
</mat-menu>

Result

Verify the result.

Menu

Details

  • As first, we've created two menus using mat-menu and bind them to buttons using matMenuTriggerFor.

  • matMenuTriggerFor is passed the menu identifier to attach the menus.

Advertisements