From b45ad2ea4fac0d4a1bc28a40440886e270e34bb9 Mon Sep 17 00:00:00 2001 From: Laxminarayan Chandrashekar <5959880+lxminarayn@users.noreply.github.com> Date: Wed, 2 Dec 2026 18:05:44 +0530 Subject: [PATCH] fix(cdk/a11y): disable configurable focus trap on destroy Destroying a ConfigurableFocusTrap deregistered it but left it enabled. A refocus queued by the event listener inert strategy just before destruction could then move focus back into the trap. The trap is now disabled when it is destroyed, so the pending refocus is skipped. --- .../a11y/focus-trap/configurable-focus-trap.ts | 2 +- .../event-listener-inert-strategy.spec.ts | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/cdk/a11y/focus-trap/configurable-focus-trap.ts b/src/cdk/a11y/focus-trap/configurable-focus-trap.ts index 26b817879e4e..3ffdc642a039 100644 --- a/src/cdk/a11y/focus-trap/configurable-focus-trap.ts +++ b/src/cdk/a11y/focus-trap/configurable-focus-trap.ts @@ -49,7 +49,7 @@ export class ConfigurableFocusTrap extends FocusTrap implements ManagedFocusTrap /** Notifies the FocusTrapManager that this FocusTrap will be destroyed. */ override destroy() { - this._focusTrapManager.deregister(this); + this.enabled = false; super.destroy(); } diff --git a/src/cdk/a11y/focus-trap/event-listener-inert-strategy.spec.ts b/src/cdk/a11y/focus-trap/event-listener-inert-strategy.spec.ts index 3c4d664ae489..29d6a1ba892b 100644 --- a/src/cdk/a11y/focus-trap/event-listener-inert-strategy.spec.ts +++ b/src/cdk/a11y/focus-trap/event-listener-inert-strategy.spec.ts @@ -64,6 +64,21 @@ describe('EventListenerFocusTrapInertStrategy', () => { .withContext('Expected second focusable element to be focused') .toBe(secondFocusableElement.nativeElement); }); + + it('should not refocus the trap if it was destroyed while a refocus was pending', async () => { + const fixture = createComponent(SimpleFocusTrap, providers); + fixture.detectChanges(); + await fixture.whenStable(); + const {focusTrap, outsideFocusableElement} = fixture.componentInstance; + + outsideFocusableElement.nativeElement.focus(); + focusTrap.destroy(); + await new Promise(resolve => setTimeout(resolve, 10)); + + expect(fixture.componentInstance.activeElement) + .withContext('Expected focus to stay outside the destroyed focus trap') + .toBe(outsideFocusableElement.nativeElement); + }); }); function createComponent(