mirror of
https://github.com/angular/angular.git
synced 2026-09-14 13:54:52 +08:00
feat(bottom-sheet): allow focus restoration to be disabled (#13153)
Similarly to `MatDialog`, allows focus restoration to be disabled for `MatBottomSheet`. Fixes #13150.
This commit is contained in:
committed by
mmalerba
parent
0cd75366c4
commit
83fc823715
@@ -49,4 +49,10 @@ export class MatBottomSheetConfig<D = any> {
|
||||
|
||||
/** Whether the bottom sheet should focus the first focusable element on open. */
|
||||
autoFocus?: boolean = true;
|
||||
|
||||
/**
|
||||
* Whether the bottom sheet should restore focus to the
|
||||
* previously-focused element, after it's closed.
|
||||
*/
|
||||
restoreFocus?: boolean = true;
|
||||
}
|
||||
|
||||
@@ -190,12 +190,12 @@ export class MatBottomSheetContainer extends BasePortalOutlet implements OnDestr
|
||||
this._focusTrap.focusInitialElementWhenReady();
|
||||
}
|
||||
|
||||
/** Restores focus to the element that was focused before the bottom sheet opened. */
|
||||
/** Restores focus to the element that was focused before the bottom sheet was opened. */
|
||||
private _restoreFocus() {
|
||||
const toFocus = this._elementFocusedBeforeOpened;
|
||||
|
||||
// We need the extra check, because IE can set the `activeElement` to null in some cases.
|
||||
if (toFocus && typeof toFocus.focus === 'function') {
|
||||
if (this.bottomSheetConfig.restoreFocus && toFocus && typeof toFocus.focus === 'function') {
|
||||
toFocus.focus();
|
||||
}
|
||||
|
||||
|
||||
@@ -567,6 +567,38 @@ describe('MatBottomSheet', () => {
|
||||
document.body.removeChild(button);
|
||||
}));
|
||||
|
||||
it('should be able to disable focus restoration', fakeAsync(() => {
|
||||
const button = document.createElement('button');
|
||||
button.id = 'bottom-sheet-trigger';
|
||||
document.body.appendChild(button);
|
||||
button.focus();
|
||||
|
||||
const bottomSheetRef = bottomSheet.open(PizzaMsg, {
|
||||
viewContainerRef: testViewContainerRef,
|
||||
restoreFocus: false
|
||||
});
|
||||
|
||||
flushMicrotasks();
|
||||
viewContainerFixture.detectChanges();
|
||||
flushMicrotasks();
|
||||
|
||||
expect(document.activeElement.id)
|
||||
.not.toBe('bottom-sheet-trigger', 'Expected the focus to change when sheet was opened.');
|
||||
|
||||
bottomSheetRef.dismiss();
|
||||
expect(document.activeElement.id).not.toBe('bottom-sheet-trigger',
|
||||
'Expcted the focus not to have changed before the animation finishes.');
|
||||
|
||||
flushMicrotasks();
|
||||
viewContainerFixture.detectChanges();
|
||||
tick(500);
|
||||
|
||||
expect(document.activeElement.id).not.toBe('bottom-sheet-trigger',
|
||||
'Expected the trigger not to be refocused on close.');
|
||||
|
||||
document.body.removeChild(button);
|
||||
}));
|
||||
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user