2
votes

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.

Stackblitz URL: https://stackblitz.com/edit/angular-mat-menu-stop-propagation?embed=1

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>

Note: If I add the stopPropagation to the checkbox, it closes the pop-over if I click outside the checkbox. So, I added in the component level.

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

1
event using stopPropagation in parent click outside closes the menu!?Fateme Fazli
@FatemeFazli - If clicking outside the menu-popover, it will close and no issues on that. If we click inside the custom component which is loaded as menu, which should not close and close only on after clicking the apply button.B.Balamanigandan

1 Answers

1
votes

Remove the stopPropagation on <menu-toolbar></menu-toolbar> and put it on the div like this:

<div (click)="$event.stopPropagation()">
    <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>