Skip to content

Commit f384cb5

Browse files
committed
fix(cdk-experimental/menu): close standalone menu when focus leaves
1 parent 5d1d36c commit f384cb5

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

src/cdk-experimental/menu/menu-item-trigger.ts

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,9 +68,11 @@ export function isClickInsideMenuOverlay(target: Element): boolean {
6868
host: {
6969
'class': 'cdk-menu-trigger',
7070
'aria-haspopup': 'menu',
71+
'[attr.aria-expanded]': 'isOpen()',
72+
'(focusin)': '_setHasFocus(true)',
73+
'(focusout)': '_setHasFocus(false)',
7174
'(keydown)': '_toggleOnKeydown($event)',
7275
'(click)': 'toggle()',
73-
'[attr.aria-expanded]': 'isOpen()',
7476
},
7577
inputs: ['_menuTemplateRef: cdkMenuTriggerFor', 'menuPosition: cdkMenuPosition'],
7678
outputs: ['opened: cdkMenuOpened', 'closed: cdkMenuClosed'],
@@ -94,6 +96,7 @@ export class CdkMenuItemTrigger extends MenuTrigger implements OnDestroy {
9496
super(injector, menuStack);
9597
this._registerCloseHandler();
9698
this._subscribeToMouseEnter();
99+
this._subscribeToHasFocus();
97100
}
98101

99102
/** Open/close the attached menu if the trigger has been configured with one */
@@ -302,4 +305,20 @@ export class CdkMenuItemTrigger extends MenuTrigger implements OnDestroy {
302305
});
303306
}
304307
}
308+
309+
private _subscribeToHasFocus() {
310+
if (!this._parentMenu) {
311+
this.menuStack.hasFocus.pipe(takeUntil(this._destroyed)).subscribe(hasFocus => {
312+
if (!hasFocus) {
313+
this.menuStack.closeAll();
314+
}
315+
});
316+
}
317+
}
318+
319+
_setHasFocus(hasFocus: boolean) {
320+
if (!this._parentMenu) {
321+
this.menuStack.setHasFocus(hasFocus);
322+
}
323+
}
305324
}

0 commit comments

Comments
 (0)