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)) {