6

I am stuck on this issue that when there a header multiple menu's and when i open a menu first time there is no issue but if there is already a menu opened and i click to open a second menu it doesn't work. it will first close the previously opened menu and then we have to click again to open the new menu.

What i want is that when i click on a menu it should open in a single click and if there is any menu opened, it closes too. I haven't found any thing regarding this in angular2 material documentation.

Below is the link for the sample of that issue:

https://stackblitz.com/edit/angular-8ntb2i

FAISAL
  • 33,618
  • 10
  • 97
  • 105
Sumit Khanduri
  • 3,619
  • 7
  • 30
  • 40
  • Today is 2021, this flaw still exists, mat-menu is not even as good as the jQuery solution! Google should be ashamed! – Pork Jackson Jan 27 '21 at 17:21

3 Answers3

3

There is no easy way to solve this issue, because when menu opens, the fullscreen overlay apllies too. The overlay is intended to detect click, then close menu and remove the overlay. As you already guessed, this overlay prevent clicks on another menu trigger and we can't open the menu, when another one is already opened.

As a workaround you can do something like this:

Catch click event on the overlay, get x and y axis, and after the overlay will be removed, you can check, does user want to click on another menu (you can use method from this post), and if so, simulate another one click at the same axis.

P.S.
  • 15,970
  • 14
  • 62
  • 86
0

You need to set z-index of menu buttons a high value (to be above the overlay).

$overlayZIndex: 1000;

.menu-item {
  z-index: $overlayZIndex + 1;
}

But when a button is clicked, the close event is no longer fired. So mannualy close the menu.

<button mat-button class="menu-item" [matMenuTriggerFor]="menu1" (click)="openMenu(0)">Menu1</button>
<mat-menu #menu1="matMenu">
  <button mat-menu-item>Item 1</button>
  <button mat-menu-item>Item 2</button>
</mat-menu>

<button mat-button class="menu-item" [matMenuTriggerFor]="menu2" (click)="openMenu(1)">Menu2</button>
<mat-menu #menu2="matMenu">
  <button mat-menu-item>Item 1</button>
  <button mat-menu-item>Item 2</button>
</mat-menu>
  @ViewChildren(MatMenuTrigger) trigger: QueryList<MatMenuTrigger>;

  constructor() { }

  openMenu(index: number) {
    this.trigger.toArray().forEach((item: MatMenuTrigger, i: number) => {
      if(i !== index && item.menuOpen) {
        item.closeMenu()
      }
    });
  }

Stackblitz

  • Had anyone succeded to make this work ? The stackblitz is working exactly as i want it to be, but when i import it in my project it doesn't work – A G Mar 18 '22 at 10:27
0

For anyone stumbling on this, there actually is a simple solution. You can just set the hasBackdrop property to false:

<mat-menu #contextMenu="matMenu" [hasBackdrop]="false"></mat-menu>
Christophe
  • 31
  • 1
  • 6