Skip to content

Commit 131272a

Browse files
crisbetojelbourn
authored andcommitted
fix(overlay): remove global keydown listener when there are no open overlays (#8389)
Removes the global `keydown` listener from the overlay dispatcher once all overlays are closed.
1 parent 2bc0b41 commit 131272a

File tree

1 file changed

+15
-4
lines changed

1 file changed

+15
-4
lines changed

src/cdk/overlay/keyboard/overlay-keyboard-dispatcher.ts

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,7 @@ export class OverlayKeyboardDispatcher implements OnDestroy {
2929
constructor(@Inject(DOCUMENT) private _document: any) {}
3030

3131
ngOnDestroy() {
32-
if (this._keydownEventSubscription) {
33-
this._keydownEventSubscription.unsubscribe();
34-
this._keydownEventSubscription = null;
35-
}
32+
this._unsubscribeFromKeydownEvents();
3633
}
3734

3835
/** Add a new overlay to the list of attached overlay refs. */
@@ -48,9 +45,15 @@ export class OverlayKeyboardDispatcher implements OnDestroy {
4845
/** Remove an overlay from the list of attached overlay refs. */
4946
remove(overlayRef: OverlayRef): void {
5047
const index = this._attachedOverlays.indexOf(overlayRef);
48+
5149
if (index > -1) {
5250
this._attachedOverlays.splice(index, 1);
5351
}
52+
53+
// Remove the global listener once there are no more overlays.
54+
if (this._attachedOverlays.length === 0) {
55+
this._unsubscribeFromKeydownEvents();
56+
}
5457
}
5558

5659
/**
@@ -68,6 +71,14 @@ export class OverlayKeyboardDispatcher implements OnDestroy {
6871
});
6972
}
7073

74+
/** Removes the global keydown subscription. */
75+
private _unsubscribeFromKeydownEvents(): void {
76+
if (this._keydownEventSubscription) {
77+
this._keydownEventSubscription.unsubscribe();
78+
this._keydownEventSubscription = null;
79+
}
80+
}
81+
7182
/** Select the appropriate overlay from a keydown event. */
7283
private _selectOverlayFromEvent(event: KeyboardEvent): OverlayRef {
7384
// Check if any overlays contain the event

0 commit comments

Comments
 (0)