From 5d7ee757432a8a00a6637f8ce8c50734d3942d1f Mon Sep 17 00:00:00 2001 From: crisbeto Date: Mon, 23 Jan 2017 20:55:54 +0100 Subject: [PATCH] fix(dialog): prevent error when restoring focus on IE * 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 #2760. --- src/lib/dialog/dialog-container.ts | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/lib/dialog/dialog-container.ts b/src/lib/dialog/dialog-container.ts index 6004809e8e05..415c6d31c1bb 100644 --- a/src/lib/dialog/dialog-container.ts +++ b/src/lib/dialog/dialog-container.ts @@ -5,6 +5,7 @@ import { ViewEncapsulation, NgZone, OnDestroy, + Renderer, } from '@angular/core'; import {BasePortalHost, ComponentPortal, PortalHostDirective, TemplatePortal} from '../core'; import {MdDialogConfig} from './dialog-config'; @@ -46,7 +47,7 @@ export class MdDialogContainer extends BasePortalHost implements OnDestroy { /** Reference to the open dialog. */ dialogRef: MdDialogRef; - constructor(private _ngZone: NgZone) { + constructor(private _ngZone: NgZone, private _renderer: Renderer) { super(); } @@ -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 . - this._ngZone.onMicrotaskEmpty.first().subscribe(() => { - (this._elementFocusedBeforeDialogWasOpened as HTMLElement).focus(); - }); + // that it doesn't end up back on the . 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'); + }); + } } }