From 6a70c7e792f40dd2464f7e4b6e7cc21fb4b8cd87 Mon Sep 17 00:00:00 2001 From: Kristiyan Kostadinov Date: Wed, 27 May 2026 09:50:53 +0200 Subject: [PATCH] fix(material/menu): close menu when cleared from trigger Fixes that the menu would get stuck in the open state if it's cleared from the trigger while it's open. Fixes #30139. --- src/material/menu/menu-trigger-base.ts | 2 ++ src/material/menu/menu.spec.ts | 16 +++++++++++++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/material/menu/menu-trigger-base.ts b/src/material/menu/menu-trigger-base.ts index beb574eee2cc..6e8bf225b59c 100644 --- a/src/material/menu/menu-trigger-base.ts +++ b/src/material/menu/menu-trigger-base.ts @@ -134,6 +134,8 @@ export abstract class MatMenuTriggerBase implements OnDestroy { this._parentMaterialMenu.closed.emit(reason); } }); + } else { + this._destroyMenu(); } this._menuItemInstance?._setTriggersSubmenu(this._triggersSubmenu()); diff --git a/src/material/menu/menu.spec.ts b/src/material/menu/menu.spec.ts index 908e6eb32ff4..969a34725eb3 100644 --- a/src/material/menu/menu.spec.ts +++ b/src/material/menu/menu.spec.ts @@ -76,7 +76,7 @@ describe('MatMenu', () => { window.scroll(0, 0); }); - it('should aria-controls the menu panel', () => { + it('should set aria-controls on the menu panel', () => { const fixture = TestBed.createComponent(SimpleMenu); fixture.detectChanges(); fixture.componentInstance.trigger.openMenu(); @@ -1149,6 +1149,20 @@ describe('MatMenu', () => { expect(Math.floor(panelRect.bottom)).toBe(viewportHeight); }); + it('should close the menu when it is cleared from the trigger', async () => { + const fixture = TestBed.createComponent(SimpleMenu); + fixture.detectChanges(); + fixture.componentInstance.trigger.openMenu(); + fixture.detectChanges(); + await wait(200); + expect(overlayContainerElement.querySelector('.mat-mdc-menu-panel')).toBeTruthy(); + + fixture.componentInstance.trigger.menu = null; + fixture.changeDetectorRef.markForCheck(); + fixture.detectChanges(); + expect(overlayContainerElement.querySelector('.mat-mdc-menu-panel')).toBeFalsy(); + }); + describe('lazy rendering', () => { it('should be able to render the menu content lazily', () => { const fixture = TestBed.createComponent(SimpleLazyMenu);