简体   繁体   中英

StopPropagation on Mat-Menu except certain click event - Angular

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM