From b98432839ef879757452a48b149fad0e289e3aae Mon Sep 17 00:00:00 2001 From: Kristiyan Kostadinov Date: Wed, 7 Aug 2024 18:34:55 +0200 Subject: [PATCH] fix(material/sidenav): disable focus trap while closed (#29548) Completely disables the sidenav's focus trap while it's closed so users can't tab to the anchors. Fixes #29545. (cherry picked from commit 626164ba5ff1b729d1d3baeef6e9dfd89566f3f4) --- src/material/sidenav/drawer.spec.ts | 23 +++++++++++++++++++++++ src/material/sidenav/drawer.ts | 2 +- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/material/sidenav/drawer.spec.ts b/src/material/sidenav/drawer.spec.ts index c917f06356b8..b8f16587393e 100644 --- a/src/material/sidenav/drawer.spec.ts +++ b/src/material/sidenav/drawer.spec.ts @@ -714,6 +714,29 @@ describe('MatDrawer', () => { .withContext('Expected focus trap anchors to be enabled in over mode.') .toBe(true); })); + + it('should disable the focus trap while closed', fakeAsync(() => { + testComponent.mode = 'over'; + fixture.changeDetectorRef.markForCheck(); + fixture.detectChanges(); + flush(); + + const anchors = Array.from( + fixture.nativeElement.querySelectorAll('.cdk-focus-trap-anchor'), + ); + expect(anchors.map(anchor => anchor.getAttribute('tabindex'))).toEqual([null, null]); + + drawer.open(); + fixture.detectChanges(); + flush(); + expect(anchors.map(anchor => anchor.getAttribute('tabindex'))).toEqual(['0', '0']); + + drawer.close(); + fixture.changeDetectorRef.markForCheck(); + fixture.detectChanges(); + flush(); + expect(anchors.map(anchor => anchor.getAttribute('tabindex'))).toEqual([null, null]); + })); }); it('should mark the drawer content as scrollable', () => { diff --git a/src/material/sidenav/drawer.ts b/src/material/sidenav/drawer.ts index 175d29f1ee38..fcd9588e697c 100644 --- a/src/material/sidenav/drawer.ts +++ b/src/material/sidenav/drawer.ts @@ -612,7 +612,7 @@ export class MatDrawer implements AfterViewInit, AfterContentChecked, OnDestroy if (this._focusTrap) { // Trap focus only if the backdrop is enabled. Otherwise, allow end user to interact with the // sidenav content. - this._focusTrap.enabled = !!this._container?.hasBackdrop; + this._focusTrap.enabled = !!this._container?.hasBackdrop && this.opened; } }