how to reverse $event.stoppropogation() on button click of mat menu in angular 14

303 Views Asked by At

I implemented an angular application (@latest version), in my implementation I used a mat-menu to show some custom component which contains some customized options along with a apply button. By default, if we do any click in the menu popover screen immediately it will close. So I added a stopPropagation on my custom component to prevent closing popover action.

But I need to close the menu pop-over on apply button click event. But its failing because the stopPropagation in the parent level prevents the button close action.

How to escape from stopPropagation only for the specified button.

File: app.component.html

<button mat-button [matMenuTriggerFor]="menu">Menu</button>
<mat-menu #menu="matMenu">
  <menu-toolbar  (click)="$event.stopPropagation()"></menu-toolbar>
</mat-menu>

File: menu-toolbar.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'menu-toolbar',
  templateUrl: './menu-toolbar.component.html',
  styleUrls: [ './menu-toolbar.component.css' ]
})
export class MenuToolbarComponent  {
  name = 'Angular';

  applyChanges(): void {
    
    // some actions done

    console.log('Changes applied successfully...');
  }
}

File: menu-toolbar.component.html

<div>
    <mat-checkbox>Item #1</mat-checkbox>
    <mat-checkbox>Item #2</mat-checkbox>
    <mat-checkbox>Item #3</mat-checkbox>
</div>
<button mat-button (click)="applyChanges($event)">Apply</button>

please assist me how to escape from stopPropagation only for the "Apply" button click.

2

There are 2 best solutions below

0
Govindamma On BEST ANSWER

I put matMenuTrigger.closeMenu() in click event, that worked for me. (click)="Submit(column.value,column.businessName);matMenuTrigger.closeMenu()"

0
Eliseo On

You can pass to your menu-toolbar the "matMenuTrigger". Then in "apply" function call to menuClose()

<!--see the #bt="matMenuTrigger"-->
<button mat-button [matMenuTriggerFor]="menu" 
         #bt="matMenuTrigger">Menu</button>

<mat-menu #menu="matMenu">
    <menu-toolbar (click)="$event.stopPropagation()" [menuTrigger]="bt">
    </menu-toolbar>
</mat-menu>

In your menu-toolbar

import {MatMenuTrigger} from '@angular/material/menu'; 

  @Input('menuTrigger')menu:MatMenuTrigger
  applyChanges(event:any): void {
    this.menu.closeMenu()
    console.log("hi")
  }

NOTE: In general, a template reference variable applied to an html element is the own html element (in this case the button). It's the reason we use

#templateRefVariable="ExportClass"

Then our template reference variable makes reference to the "directive", so we can use all the methods of the directive. If you see the docs about matMenuTrigger you see the "Exported as: matMenuTrigger"