feat(dialog): allow focus restoration to be disabled (#12519)

This commit is contained in:
Kristiyan Kostadinov
2018-08-08 23:40:12 +02:00
committed by Joey Perrott
parent 5a560b2ff3
commit d5c5f317b0
3 changed files with 38 additions and 1 deletions
+6
View File
@@ -95,6 +95,12 @@ export class MatDialogConfig<D = any> {
/** Whether the dialog should focus the first focusable element on open. */
autoFocus?: boolean = true;
/**
* Whether the dialog should restore focus to the
* previously-focused element, after it's closed.
*/
restoreFocus?: boolean = true;
/** Scroll strategy to be used for the dialog. */
scrollStrategy?: ScrollStrategy;
+1 -1
View File
@@ -148,7 +148,7 @@ export class MatDialogContainer extends BasePortalOutlet {
const toFocus = this._elementFocusedBeforeDialogWasOpened;
// We need the extra check, because IE can set the `activeElement` to null in some cases.
if (toFocus && typeof toFocus.focus === 'function') {
if (this._config.restoreFocus && toFocus && typeof toFocus.focus === 'function') {
toFocus.focus();
}
+31
View File
@@ -1009,6 +1009,37 @@ describe('MatDialog', () => {
.toBe('MAT-DIALOG-CONTAINER', 'Expected dialog container to be focused.');
}));
it('should be able to disable focus restoration', fakeAsync(() => {
// Create a element that has focus before the dialog is opened.
const button = document.createElement('button');
button.id = 'dialog-trigger';
document.body.appendChild(button);
button.focus();
const dialogRef = dialog.open(PizzaMsg, {
viewContainerRef: testViewContainerRef,
restoreFocus: false
});
flushMicrotasks();
viewContainerFixture.detectChanges();
flushMicrotasks();
expect(document.activeElement.id)
.not.toBe('dialog-trigger', 'Expected the focus to change when dialog was opened.');
dialogRef.close();
flushMicrotasks();
viewContainerFixture.detectChanges();
tick(500);
expect(document.activeElement.id).not.toBe('dialog-trigger',
'Expected focus not to have been restored.');
document.body.removeChild(button);
}));
});
describe('dialog content elements', () => {