What is the best way to determine if a mat-menu in Material Angular is currently displaying or hidden?

Is there a way to determine if the mat-menu is currently open so that I can dynamically apply a class to the corresponding button using [ngClass] depending on the menu's state?

<button mat-stroked-button mdbWavesEffect [matMenuTriggerFor]="menu">Actions</button>
    <mat-menu #menu="matMenu" [overlapTrigger]="false" panelClass="custom">
        <a routerLink="/attendence/detail" mat-menu-item>View Attendance</a>
        <a routerLink="/adherence/detail" mat-menu-item>View Adherece</a>
        <button mat-menu-item>Edit Agent</button>
        <button mat-menu-item>Upload photo</button>
        <button mat-menu-item>Deactivate Agent</button>
    </mat-menu>

Answer №1

If you want to determine whether the menu is open or not, you can utilize the Material matMenuTrigger directive.

<button mat-button [matMenuTriggerFor]="menu"   #t="matMenuTrigger">Menu</button>
<mat-menu #menu="matMenu">
  <button mat-menu-item>Item 1</button>
  <button mat-menu-item>Item 2</button>
</mat-menu>
{{t.menuOpen}}

Take a look at this example for reference: https://stackblitz.com/edit/angular-9hbzdw

You can also use ngClass binding to dynamically change the style of your button!

Answer №2

If you want to trigger a method when the Menu is opened, you can bind it to the "menuOpened" event.

<mat-menu #menu="matMenu" [overlapTrigger]="false" (menuOpened)="isOpened($event)" panelClass="custom">
                    <a routerLink="/attendence/detail" mat-menu-item>View Attendance</a>
                    <a routerLink="/adherence/detail" mat-menu-item>View Adherece</a>
                    <button mat-menu-item>Edit Agent</button>
                    <button mat-menu-item>Upload photo</button>
                    <button mat-menu-item>Deactivate Agent</button>
                </mat-menu>

Don't forget to add the "isOpened" method in your component:

isOpened(evt:any){
    // Set a flag here that you can use in ng-class for the buttons.
}

I hope this explanation was helpful to you.

Answer №3

At times, you may encounter an issue with the mat-menu in your Angular application that is using onPush changeDetection. In such situations, it is essential to inform Angular whether the menu is open or closed.

Angular Material provides events to determine the status of the menu:

  1. menuOpened: Triggered when the menu is opened.
  2. menuClosed: Fired when the menu is closed.

Below is the code snippet illustrating this:

<button mat-button #menuOption="matMenuTrigger" [matMenuTriggerFor]="menu"
            (menuOpened)="menuOption.menuOpen" (menuClosed)="menuOption.menuOpen">
      Menu
      <span>{{menuOption.menuOpen ? 'open': 'closed'}}</span>
</button>

Answer №4

I encountered a similar situation and found a solution using CSS.

When the menu is clicked, a custom aria tag is added to the menu and then removed when the dropdown is closed. This allows us to utilize a CSS custom selector (compatible with most modern browsers).

.parentclass a[aria-expanded] { apply your styling here }

In some cases (for buttons):

.parentclass button[aria-expanded] { apply your styling here }

Thank you,

Answer №5

 <button mat-stroked-button mdbWavesEffect [matMenuTriggerFor]="menu">Actions</button>
            <mat-menu #menu="matMenu" [overlapTrigger]="false" panelClass="custom">
                <a routerLink="/attendence/detail" mat-menu-item>View Attendance</a>
                <a routerLink="/adherence/detail" mat-menu-item>View Adherece</a>
                <button [ngClass]="selectedMenuItem ===1 ? 'active' : ''" (click)="onSelectMenuItem(1)" mat-menu-item>Edit Agent</button>
                <button [ngClass]="selectedMenuItem ===2 ? 'active' : ''" (click)="onSelectMenuItem(2)" mat-menu-item>Upload photo</button>
                <button [ngClass]="selectedMenuItem ===3 ? 'active' : ''" (click)="onSelectMenuItem(3)" mat-menu-item>Deactivate Agent</button>
            </mat-menu>

selectedMenuItem  = 1 // Starting with a default value of 1
 onSelectMenuItem(id): void {
    this.selectedMenuItem = id;
 }

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: When attempting to integrate a Flask Backend with a NextJS frontend, encountering issues with files not being received properly

I have developed a Flask Backend with the purpose of accepting and processing files. Recently, I created a Next.js frontend where users can upload files. Strangely enough, when I followed the same steps as in my Flask project using a template HTML file, it ...

Issues with launching project following updates to Angular-cli

After updating npm, node, and angular-cli to the latest versions, I encountered an issue when running the ng serve command in my existing project. ERROR in ./src/main.ts Module build failed: TypeError: Cannot read property 'newLine' of undefined ...

How about: "Loop through an array of objects fetched from an observable and initiate an HTTP request for each object's ID?"

Using Angular routing, in the component's ngOnInit method, I retrieve a genre ID through an observable. Within this observable, a service method is called that makes an HTTP request. this.movies: Movie[]; ngOnInit() { this.route.paramMap.sub ...

Issue: CSS breaking in Node.js Express app when navigating with multiple child paths or parameter paths in the route.Description: Encounter

When attempting to load a page like /patient_profile, the CSS loads correctly. However, when continuing the path to /patient_profile/settings_patient_profile, the CSS breaks. Both pages mentioned are the same file, just testing the routing. The route is m ...

Sending information to a deeply nested child component in Angular 4

Here is the structure of components in my Angular application: app.component.html units.component.html section.component.html {{appData.title}} I have created "appData" in the app.component.ts and now I want to access it in the third level child co ...

Encountering a validation error when attempting to submit the form

I am facing an issue with my form. Inside the form, I have a dropdown menu that dynamically displays a textbox upon selection. The form also includes an array feature to allow for multiple textboxes to be displayed. Despite filling in all fields with value ...

What causes block elements to act like inline elements?

:target { border: 2px solid #D4D4D4; background-color: #e5eecc; } .navigation li { list-style-type: none; float: left; padding: 1em; } <ul class="navigation"> <li> <a href="#help"> Help </a> </li> <li> & ...

Guide on associating an array of object keys with an array of their corresponding values within a specified object

const obj = { wheels: 4, lights: 2, doors: 4 } customMapFunction(obj, { properties: ["wheels", "lights"], formatter: (wheels, lights) => `${wheels}-${lights}` // "4-2" }) How do I define the types for customMapFunction in TypeScript to ensure th ...

To modify the pageSize of the KendoGrid in order to display 1-10 out of 100, you can customize the appearance and functionality of the page numbers by changing

I am currently working on a kendo grid that utilizes the traditional [kendoGridBinding]="gridData" method as shown below - `<kendo-grid #grid [kendoGridBinding]="gridData" [pageable]="true" [pageSize]="5" style="cursor:pointer"> <kendo-grid ...

Turn off hover opacity effect for a specific image

Currently, I've implemented a hover opacity effect on my images using the following CSS: img { opacity: 1.0; filter: alpha(opacity=1.0); } img:hover { opacity: 0.6; filter: alpha(opacity=0.6); } However, I now have a specific image for whi ...

Guide to synchronizing schema changes for legacy document collections in MongoDB using default values

Is there a way to implement schema changes in mongodb and sync them with default values for all existing data? import mongoose from "mongoose"; interface ITodo { title: string; description: string; by: string; } interface todoModelInterfa ...

objects continue to escape the confines of the container

While working on this dashboard design, I've encountered an issue where the content items jump out of their designated container. I'm using Bootstrap and have tried various solutions like setting the class to container-fluid, changing tags from & ...

Adjust the Express JS response to prevent certain specific values from being included

I am currently working on an Express application that is returning large decimal numbers as text in the responses. The issue arises when the numbers are either 'Infinity' or 'NaN'. I am looking for a way to replace these values with emp ...

A guide on incorporating a JavaScript plugin using Vue.use() into a TypeScript project equipped with typings

Currently, I am facing an issue while attempting to integrate Semantic-UI-Vue into my Vue project. Upon trying to execute Vue.use(SuiVue), the following error message is displayed: Argument of type 'typeof import("semantic-ui-vue")' is not ass ...

Tips for generating a fixed-length array from multiple arrays with different lengths, focusing on selecting items from each array according to their significance

In order to create a quiz, I am looking to extract 'questions' from various 'topic' arrays. These topics are selected based on the user's preference and are used to populate a question bank for a 20-question quiz. The topics rated ...

Is there a way to create a mobile-exclusive slideshow using JavaScript?

I am trying to create a slideshow on my website, but whenever I add JavaScript it seems to break the desktop version. I want these three pictures to remain static and only start sliding when viewed on a mobile device. I have searched for resources on how t ...

Using ts-loader with Webpack 2 will result in compatibility issues

Lately, I've been working on setting up a basic Angular 2 (TypeScript) application with Webpack 2 for bundling. However, I'm encountering numerous errors when using ts-loader to process TypeScript (.ts) files. It seems like ts-loader is not excl ...

Tips for updating the barchart legend in an Angular application

Is there a way to switch the position of the legend from top to bottom in an nvd3 chart? https://i.sstatic.net/gWMFf.png options = { "chart": { "type": "multiBarChart", "height": 300, "margin": { "top": 20, "right": 20, "bottom": 45, ...

Enhance your website navigation with Bootstrap Scrolling Nav: maintain consistent section heights and highlight the active

Can you help me with an issue I'm having when clicking on the <a> link in the navigation? The anchor point seems to be misplaced as the section headline (<h2>) is not visible. Is there a way to highlight the <a> links, perhaps by add ...

Bootstrap: the rows are breaching the boundaries of their parent containers, causing them to overlap with

I'm struggling to create a bootstrap layout similar to the one on Codepen. Everything looks good on the codepen demo: Codepen_bootstrap ...but when I try to view the page locally in my browser (Chrome and Safari), the design becomes distorted and el ...