What is the best way to trigger a mat-menu to open with just one click, while also automatically closing any other open menus at

I've encountered an issue where if there are multiple menus in the header, opening a menu for the first time works fine. However, if a menu is already open and I try to open another one, it doesn't work as expected. It closes the previously opened menu first, requiring an additional click to open the new menu.

What I'm looking for is a solution where clicking on a menu opens it with a single click, closing any previously opened menu at the same time. Unfortunately, I haven't been able to find any information on this in the Angular2 Material documentation.

You can check out a sample of this issue by following this link:

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

Answer №1

Dealing with this issue is not a straightforward task, especially since the fullscreen overlay comes into play when the menu opens. The purpose of the overlay is to capture clicks in order to close the menu and remove the overlay. Consequently, this overlay interferes with the ability to click on another menu trigger while one menu is already open.

One potential workaround involves:

Intercepting the click event on the overlay, recording the x and y coordinates, removing the overlay, and then checking if the user intends to click on another menu (you can refer to the method outlined in this helpful post). If necessary, simulate another click at the same coordinates to trigger the next menu.

Answer №2

If you happen to come across this issue, fear not! There is actually a straightforward solution available. Simply adjust the hasBackdrop property to false:

<mat-menu #contextMenu="matMenu" [hasBackdrop]="false"></mat-menu>

Answer №3

To ensure the menu buttons are displayed above the overlay, set a high z-index value for them.

$overlayZIndex: 1000;

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

However, when a button is clicked, the close event may not trigger automatically. In such cases, manually 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()
      }
    });
  }

Check out the code on Stackblitz

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting Gitlab CI/CD freezing upon committing updates

Hey there, I'm running into an issue while setting up Gitlab CI/CD with the Angular ng test command. The pipeline starts as expected, but then it gets stuck. I understand that Karma relies on chrome. I seem to be missing something. Any advice would b ...

Creating a React component with multiple prop types using Typescript

In this particular component, the requirement is to input a config object that can be of two types - either an object containing a "name" property (which should be a string), or a boolean value indicating that the config object has not been set yet. type C ...

Trouble arises with connect-mongo, passport, and passport-local-mongoose as session fails to persist

Seeking assistance with saving session and incorporating functionality like req.isAuthenticated(), req.user, etc., but unable to make it work. Session does not persist and seems to be malfunctioning for unknown reasons. app.ts https://pastebin.com/yGvUZh ...

Error: The current call does not match any existing overloads - TypeScript, NextJS, styled-components

I'm facing an issue while trying to display icons in the footer of my website. The error message "Type error: No overload matches this call" keeps appearing next to my StyledIconsWrapper component, causing Vercel deployment to fail. Despite this error ...

Get the final element with a for loop in Angular 2

I am currently utilizing angular 2 in conjunction with mongoDb. The service I am employing is responsible for calling the API. Here is a snippet of my code: this.at represents a token, similar to fdfdsfdffsdf... This token serves as an authorization key ...

Storing Passport.js Token Locally: Best Practices

Struggling to save the jwt token provided by passport.js in browser localStorage, I am facing challenges with transferring it from the server to the client as it is generated on the server side. If anyone can assist me with setting the server-generated to ...

Error message stating: "Form control with the name does not have a value accessor in Angular's reactive forms."

I have a specific input setup in the following way: <form [formGroup]="loginForm""> <ion-input [formControlName]="'email'"></ion-input> In my component, I've defined the form as: this.log ...

Nest is having trouble resolving dependencies for this service

Can multiple MongoDB models be injected into one resolver and used? I attempted to accomplish this by first adding the import of SectionSchema and SectionsService to the PostsModule: @Module({ imports: [MongooseModule.forFeature([{name: 'Post&apos ...

What is the best method for transitioning to a new page in React Native using Ignite Bowser?

Recently I ventured into the world of React Native with Ignite Bowser. My current project involves building a React Native app using Ignite Bowser. At the start of my app, there's a welcoming screen that pops up. It features a 'continue' bu ...

Having trouble displaying nested routes in Angular within the view

I'm encountering some issues with child/nested routes in Angular 4. In the app.module.ts file, my imports statement looks like this: RouterModule.forRoot([ { path: 'templates', component: TemplateLandingC ...

What is the best way to transfer data from .ts and .html files to css/scss in an Angular

I'm currently working on a MEAN stack application and I would like to allow users to customize the theme color. The selected color should be saved in MongoDB so that every time the user opens the application, it remains consistent. I would appreciate ...

Utilizing the useSelect hook in Typescript to create custom types for WordPress Gutenberg, specifically targeting the core/editor

As I delve into development with WordPress and the Gutenberg editor, my goal is to incorporate TypeScript into the mix. However, I encounter a type error when trying to utilize the useSelect() hook in conjunction with an associated function from the core/e ...

Is there a way to upgrade Angular from version 15 to 16 without encountering issues with ESBuild getting blocked and causing the update to fail?

I have been attempting to upgrade Angular from version 15 to version 16. However, when I execute the command ng update @angular/core@16 @angular/cli@16, it initiates the update process but at a certain point, "ESBuild.exe" is triggered and my "ThreatLocker ...

Error Encountered when Trying to Utilize Vue Component Getter in TypeScript Mixin (Error Code: TS233

Here is the code snippet that I am currently working with: import {Component, Vue} from 'vue-property-decorator'; @Component({}) export default class MyMixin extends Vue { scrollToTop(): void { let scrollingWrapper: any = (this.$refs[th ...

Attempting to retrieve a file from the database with the utilization of Angular 5 and ASP.NET Core

I've been struggling with downloading a file from the database using its unique identifier. Can anyone provide guidance on what steps are necessary to achieve this successfully? The FileUpload table contains the following columns pertaining to the fi ...

"Encountering a 'ng not found' issue while constructing an Angular application with a

Yesterday, I encountered a strange issue while working on an Angular project and deploying it using Docker. Everything was running smoothly until suddenly I hit a roadblock - I couldn't build the Docker image anymore. Here's my Dockerfile: # Stag ...

"Converting to Typescript resulted in the absence of a default export in the module

I converted the JavaScript code to TypeScript and encountered an issue: The module has no default export I tried importing using curly braces and exporting with module.exports, but neither solution worked. contactController.ts const contacts: String[ ...

Concealing applicationId and clientToken in Datadog

I'm currently using an Angular application and I've integrated it with the Datadog application to utilize Session and Replay (RUM). However, I am concerned about the security of my sensitive information such as applicationId and clientToken. Is t ...

Checking the value of a row in an Angular Material table when a checkbox is

I am working with an Angular Material table that has rows with checkboxes. To view the example of this, please visit Material Table. I would like to perform a manipulation on other fields based on the checkbox selection status of a row. ...

Angular: Modules that are lazily loaded are only loaded into memory and executed, but

I am facing an issue with lazy loading in my Angular application. I have an AppModule that lazily loads MainModule, which in turn lazy loads HomeModule. The problem is that while MainModule loads fine, HomeModule gets loaded but is not rendered inside the ...