Skip to content

fix(menu): not closed correctly if opened by different trigger while visible #15373

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/material/menu/menu-panel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export interface MatMenuPanel<T = any> {
focusFirstItem: (origin?: FocusOrigin) => void;
resetActiveItem: () => void;
setPositionClasses?: (x: MenuPositionX, y: MenuPositionY) => void;
openedBy?: EventEmitter<any>;
setElevation?(depth: number): void;
lazyContent?: MatMenuContent;
backdropClass?: string;
Expand Down
29 changes: 21 additions & 8 deletions src/material/menu/menu-trigger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ import {
isDevMode,
} from '@angular/core';
import {normalizePassiveListenerOptions} from '@angular/cdk/platform';
import {asapScheduler, merge, of as observableOf, Subscription} from 'rxjs';
import {asapScheduler, merge, of as observableOf, Subscription, Subject} from 'rxjs';
import {delay, filter, take, takeUntil} from 'rxjs/operators';
import {MatMenu} from './menu';
import {throwMatMenuMissingError, throwMatMenuRecursiveError} from './menu-errors';
Expand Down Expand Up @@ -87,7 +87,7 @@ export class MatMenuTrigger implements AfterContentInit, OnDestroy {
private _menuOpen: boolean = false;
private _closingActionsSubscription = Subscription.EMPTY;
private _hoverSubscription = Subscription.EMPTY;
private _menuCloseSubscription = Subscription.EMPTY;
private _menuChanged = new Subject<void>();
private _scrollStrategy: () => ScrollStrategy;

/**
Expand Down Expand Up @@ -119,14 +119,22 @@ export class MatMenuTrigger implements AfterContentInit, OnDestroy {
}

this._menu = menu;
this._menuCloseSubscription.unsubscribe();
this._menuChanged.next();

if (menu) {
if (isDevMode() && menu === this._parentMenu) {
throwMatMenuRecursiveError();
}

this._menuCloseSubscription = menu.close.asObservable().subscribe(reason => {
if (menu.openedBy) {
menu.openedBy.pipe(takeUntil(this._menuChanged)).subscribe((reason?: MatMenuTrigger) => {
if (reason && reason !== this) {
this._destroyMenu();
}
});
}

menu.close.pipe(takeUntil(this._menuChanged)).subscribe(reason => {
this._destroyMenu();

// If a click closed the menu, we should close the entire chain of nested menus.
Expand Down Expand Up @@ -209,9 +217,9 @@ export class MatMenuTrigger implements AfterContentInit, OnDestroy {
this._element.nativeElement.removeEventListener('touchstart', this._handleTouchStart,
passiveEventListenerOptions);

this._menuCloseSubscription.unsubscribe();
this._closingActionsSubscription.unsubscribe();
this._hoverSubscription.unsubscribe();
this._menuChanged.complete();
}

/** Whether the menu is open. */
Expand Down Expand Up @@ -324,11 +332,16 @@ export class MatMenuTrigger implements AfterContentInit, OnDestroy {
* the menu was opened via the keyboard.
*/
private _initMenu(): void {
this.menu.parentMenu = this.triggersSubmenu() ? this._parentMenu : undefined;
this.menu.direction = this.dir;
const menu = this.menu;
menu.parentMenu = this.triggersSubmenu() ? this._parentMenu : undefined;
menu.direction = this.dir;
this._setMenuElevation();
this._setIsMenuOpen(true);
this.menu.focusFirstItem(this._openedBy || 'program');
menu.focusFirstItem(this._openedBy || 'program');

if (menu.openedBy) {
menu.openedBy.emit(this);
}
}

/** Updates the menu elevation based on the amount of parent menus that it has. */
Expand Down
30 changes: 30 additions & 0 deletions src/material/menu/menu.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -905,6 +905,22 @@ describe('MatMenu', () => {
expect(document.activeElement).toBe(overlayContainerElement.querySelector('.mat-menu-panel'));
}));

it('should close the menu if it is opened by a different trigger', fakeAsync(() => {
const fixture = createComponent(MenuWithMultipleTriggers);
fixture.detectChanges();

fixture.componentInstance.triggers.first.openMenu();
fixture.detectChanges();
flush();
expect(overlayContainerElement.querySelectorAll('.mat-menu-panel').length).toBe(1);

fixture.componentInstance.triggers.last.openMenu();
fixture.detectChanges();
flush();
expect(overlayContainerElement.querySelectorAll('.mat-menu-panel').length).toBe(1);

}));

describe('lazy rendering', () => {
it('should be able to render the menu content lazily', fakeAsync(() => {
const fixture = createComponent(SimpleLazyMenu);
Expand Down Expand Up @@ -2640,3 +2656,17 @@ class LazyMenuWithOnPush {
})
class InvalidRecursiveMenu {
}

@Component({
template: `
<button [matMenuTriggerFor]="menu">First trigger</button>
<button [matMenuTriggerFor]="menu">Second trigger</button>
<mat-menu #menu="matMenu">
<button mat-menu-item>Item one</button>
<button mat-menu-item>Item two</button>
</mat-menu>
`
})
class MenuWithMultipleTriggers {
@ViewChildren(MatMenuTrigger) triggers: QueryList<MatMenuTrigger>;
}
8 changes: 8 additions & 0 deletions src/material/menu/menu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,13 @@ export class _MatMenuBase implements AfterContentInit, MatMenuPanel<MatMenuItem>
@Output() readonly closed: EventEmitter<void | 'click' | 'keydown' | 'tab'> =
new EventEmitter<void | 'click' | 'keydown' | 'tab'>();


/**
* Stream that emits the trigger that the menu was opened by.
* @docs-private
*/
@Output() openedBy = new EventEmitter<any>();

/**
* Event emitted when the menu is closed.
* @deprecated Switch to `closed` instead
Expand Down Expand Up @@ -281,6 +288,7 @@ export class _MatMenuBase implements AfterContentInit, MatMenuPanel<MatMenuItem>
this._directDescendantItems.destroy();
this._tabSubscription.unsubscribe();
this.closed.complete();
this.openedBy.complete();
}

/** Stream that emits whenever the hovered menu item changes. */
Expand Down
4 changes: 3 additions & 1 deletion tools/public_api_guard/material/menu.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export declare class _MatMenuBase implements AfterContentInit, MatMenuPanel<MatM
set hasBackdrop(value: boolean | undefined);
items: QueryList<MatMenuItem>;
lazyContent: MatMenuContent;
openedBy: EventEmitter<any>;
get overlapTrigger(): boolean;
set overlapTrigger(value: boolean);
overlayPanelClass: string | string[];
Expand Down Expand Up @@ -54,7 +55,7 @@ export declare class _MatMenuBase implements AfterContentInit, MatMenuPanel<MatM
setPositionClasses(posX?: MenuPositionX, posY?: MenuPositionY): void;
static ngAcceptInputType_hasBackdrop: BooleanInput;
static ngAcceptInputType_overlapTrigger: BooleanInput;
static ɵdir: i0.ɵɵDirectiveDefWithMeta<_MatMenuBase, never, never, { "backdropClass": "backdropClass"; "ariaLabel": "aria-label"; "ariaLabelledby": "aria-labelledby"; "ariaDescribedby": "aria-describedby"; "xPosition": "xPosition"; "yPosition": "yPosition"; "overlapTrigger": "overlapTrigger"; "hasBackdrop": "hasBackdrop"; "panelClass": "class"; "classList": "classList"; }, { "closed": "closed"; "close": "close"; }, ["lazyContent", "_allItems", "items"]>;
static ɵdir: i0.ɵɵDirectiveDefWithMeta<_MatMenuBase, never, never, { "backdropClass": "backdropClass"; "ariaLabel": "aria-label"; "ariaLabelledby": "aria-labelledby"; "ariaDescribedby": "aria-describedby"; "xPosition": "xPosition"; "yPosition": "yPosition"; "overlapTrigger": "overlapTrigger"; "hasBackdrop": "hasBackdrop"; "panelClass": "class"; "classList": "classList"; }, { "closed": "closed"; "openedBy": "openedBy"; "close": "close"; }, ["lazyContent", "_allItems", "items"]>;
static ɵfac: i0.ɵɵFactoryDef<_MatMenuBase, never>;
}

Expand Down Expand Up @@ -137,6 +138,7 @@ export interface MatMenuPanel<T = any> {
focusFirstItem: (origin?: FocusOrigin) => void;
hasBackdrop?: boolean;
lazyContent?: MatMenuContent;
openedBy?: EventEmitter<any>;
overlapTrigger: boolean;
overlayPanelClass?: string | string[];
readonly panelId?: string;
Expand Down