Skip to content

Commit

Permalink
fix(dialog): prevent error when restoring focus on IE
Browse files Browse the repository at this point in the history
* Adds an extra null check when restoring focus after a dialog is closed. This is necessary, because the `document.activeElement` can be null in IE.
* Switches the focusing logic to use the `Renderer`.

Fixes angular#2760.
  • Loading branch information
crisbeto committed Jan 23, 2017
1 parent 592f33f commit 5d7ee75
Showing 1 changed file with 9 additions and 5 deletions.
14 changes: 9 additions & 5 deletions src/lib/dialog/dialog-container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
ViewEncapsulation,
NgZone,
OnDestroy,
Renderer,
} from '@angular/core';
import {BasePortalHost, ComponentPortal, PortalHostDirective, TemplatePortal} from '../core';
import {MdDialogConfig} from './dialog-config';
Expand Down Expand Up @@ -46,7 +47,7 @@ export class MdDialogContainer extends BasePortalHost implements OnDestroy {
/** Reference to the open dialog. */
dialogRef: MdDialogRef<any>;

constructor(private _ngZone: NgZone) {
constructor(private _ngZone: NgZone, private _renderer: Renderer) {
super();
}

Expand Down Expand Up @@ -90,9 +91,12 @@ export class MdDialogContainer extends BasePortalHost implements OnDestroy {
ngOnDestroy() {
// When the dialog is destroyed, return focus to the element that originally had it before
// the dialog was opened. Wait for the DOM to finish settling before changing the focus so
// that it doesn't end up back on the <body>.
this._ngZone.onMicrotaskEmpty.first().subscribe(() => {
(this._elementFocusedBeforeDialogWasOpened as HTMLElement).focus();
});
// that it doesn't end up back on the <body>. Also note that we need the extra check, because
// IE can set the `activeElement` to null in some cases.
if (this._elementFocusedBeforeDialogWasOpened) {
this._ngZone.onMicrotaskEmpty.first().subscribe(() => {
this._renderer.invokeElementMethod(this._elementFocusedBeforeDialogWasOpened, 'focus');
});
}
}
}

0 comments on commit 5d7ee75

Please sign in to comment.