Skip to content

Commit

Permalink
feat(dialog): allow focus restoration to be disabled (#12519)
Browse files Browse the repository at this point in the history
  • Loading branch information
crisbeto authored and josephperrott committed Aug 8, 2018
1 parent 0df820c commit 458ac4d
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 1 deletion.
6 changes: 6 additions & 0 deletions src/lib/dialog/dialog-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
2 changes: 1 addition & 1 deletion src/lib/dialog/dialog-container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}

Expand Down
31 changes: 31 additions & 0 deletions src/lib/dialog/dialog.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down

0 comments on commit 458ac4d

Please sign in to comment.