Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 1 commit into from
Aug 8, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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