Skip to content

Commit d5c5f31

Browse files
crisbetojosephperrott
authored andcommitted
feat(dialog): allow focus restoration to be disabled (#12519)
1 parent 5a560b2 commit d5c5f31

File tree

3 files changed

+38
-1
lines changed

3 files changed

+38
-1
lines changed

src/lib/dialog/dialog-config.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,12 @@ export class MatDialogConfig<D = any> {
9595
/** Whether the dialog should focus the first focusable element on open. */
9696
autoFocus?: boolean = true;
9797

98+
/**
99+
* Whether the dialog should restore focus to the
100+
* previously-focused element, after it's closed.
101+
*/
102+
restoreFocus?: boolean = true;
103+
98104
/** Scroll strategy to be used for the dialog. */
99105
scrollStrategy?: ScrollStrategy;
100106

src/lib/dialog/dialog-container.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ export class MatDialogContainer extends BasePortalOutlet {
148148
const toFocus = this._elementFocusedBeforeDialogWasOpened;
149149

150150
// We need the extra check, because IE can set the `activeElement` to null in some cases.
151-
if (toFocus && typeof toFocus.focus === 'function') {
151+
if (this._config.restoreFocus && toFocus && typeof toFocus.focus === 'function') {
152152
toFocus.focus();
153153
}
154154

src/lib/dialog/dialog.spec.ts

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1009,6 +1009,37 @@ describe('MatDialog', () => {
10091009
.toBe('MAT-DIALOG-CONTAINER', 'Expected dialog container to be focused.');
10101010
}));
10111011

1012+
it('should be able to disable focus restoration', fakeAsync(() => {
1013+
// Create a element that has focus before the dialog is opened.
1014+
const button = document.createElement('button');
1015+
button.id = 'dialog-trigger';
1016+
document.body.appendChild(button);
1017+
button.focus();
1018+
1019+
const dialogRef = dialog.open(PizzaMsg, {
1020+
viewContainerRef: testViewContainerRef,
1021+
restoreFocus: false
1022+
});
1023+
1024+
flushMicrotasks();
1025+
viewContainerFixture.detectChanges();
1026+
flushMicrotasks();
1027+
1028+
expect(document.activeElement.id)
1029+
.not.toBe('dialog-trigger', 'Expected the focus to change when dialog was opened.');
1030+
1031+
dialogRef.close();
1032+
flushMicrotasks();
1033+
viewContainerFixture.detectChanges();
1034+
tick(500);
1035+
1036+
expect(document.activeElement.id).not.toBe('dialog-trigger',
1037+
'Expected focus not to have been restored.');
1038+
1039+
document.body.removeChild(button);
1040+
}));
1041+
1042+
10121043
});
10131044

10141045
describe('dialog content elements', () => {

0 commit comments

Comments
 (0)