From ad42f457daf2d2edd06525b3a7a4a87e1b2508cf Mon Sep 17 00:00:00 2001 From: crisbeto Date: Fri, 20 Apr 2018 11:06:21 -0600 Subject: [PATCH] feat(sidenav): allow for auto focusing to be disabled Along the same lines as the dialog, these changes allow for the auto focusing, that is done by the sidenav, to be disabled. Fixes #10402. --- src/lib/sidenav/drawer.spec.ts | 16 +++++++++++++++- src/lib/sidenav/drawer.ts | 14 ++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/src/lib/sidenav/drawer.spec.ts b/src/lib/sidenav/drawer.spec.ts index 4c6dabea2ad9..b7ae971aabda 100644 --- a/src/lib/sidenav/drawer.spec.ts +++ b/src/lib/sidenav/drawer.spec.ts @@ -469,6 +469,19 @@ describe('MatDrawer', () => { expect(document.activeElement).toBe(drawerEl.nativeElement); })); + it('should be able to disable auto focus', fakeAsync(() => { + testComponent.autoFocus = false; + testComponent.mode = 'push'; + fixture.detectChanges(); + lastFocusableElement.focus(); + + drawer.open(); + fixture.detectChanges(); + tick(); + + expect(document.activeElement).not.toBe(firstFocusableElement); + })); + }); }); @@ -790,7 +803,7 @@ class DrawerDynamicPosition { // to be focusable across all platforms. template: ` - + @@ -798,6 +811,7 @@ class DrawerDynamicPosition { }) class DrawerWithFocusableElements { mode: string = 'over'; + autoFocus = true; } @Component({ diff --git a/src/lib/sidenav/drawer.ts b/src/lib/sidenav/drawer.ts index d0bbf4cb4eb3..076d4e143333 100644 --- a/src/lib/sidenav/drawer.ts +++ b/src/lib/sidenav/drawer.ts @@ -150,6 +150,12 @@ export class MatDrawer implements AfterContentInit, AfterContentChecked, OnDestr set disableClose(value: boolean) { this._disableClose = coerceBooleanProperty(value); } private _disableClose: boolean = false; + /** Whether the drawer should focus the first focusable element automatically when opened. */ + @Input() + get autoFocus(): boolean { return this._autoFocus; } + set autoFocus(value: boolean) { this._autoFocus = coerceBooleanProperty(value); } + private _autoFocus: boolean = true; + /** How the sidenav was opened (keypress, mouse click etc.) */ private _openedVia: FocusOrigin | null; @@ -246,6 +252,10 @@ export class MatDrawer implements AfterContentInit, AfterContentChecked, OnDestr /** Traps focus inside the drawer. */ private _trapFocus() { + if (!this.autoFocus) { + return; + } + this._focusTrap.focusInitialElementWhenReady().then(hasMovedFocus => { // If there were no focusable elements, focus the sidenav itself so the keyboard navigation // still works. We need to check that `focus` is a function due to Universal. @@ -260,6 +270,10 @@ export class MatDrawer implements AfterContentInit, AfterContentChecked, OnDestr * opened. */ private _restoreFocus() { + if (!this.autoFocus) { + return; + } + const activeEl = this._doc && this._doc.activeElement; if (activeEl && this._elementRef.nativeElement.contains(activeEl)) {