Skip to content

Commit

Permalink
fix(dialog): capture previously focused element immediately
Browse files Browse the repository at this point in the history
Captures the previously-focused element immediately, instead of waiting until the animation is done. This fixes a regression from angular#3774, because if we wait for the animation to finish, the focus might have shifted, or the element could have been disabled.
  • Loading branch information
crisbeto committed Apr 2, 2017
1 parent f40296e commit 0098279
Showing 1 changed file with 17 additions and 2 deletions.
19 changes: 17 additions & 2 deletions src/lib/dialog/dialog-container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import {
Renderer,
ElementRef,
EventEmitter,
Inject,
Optional,
} from '@angular/core';
import {
animate,
Expand All @@ -17,6 +19,7 @@ import {
transition,
AnimationEvent,
} from '@angular/animations';
import {DOCUMENT} from '@angular/platform-browser';
import {BasePortalHost, ComponentPortal, PortalHostDirective, TemplatePortal} from '../core';
import {MdDialogConfig} from './dialog-config';
import {MdDialogContentAlreadyAttachedError} from './dialog-errors';
Expand Down Expand Up @@ -77,7 +80,8 @@ export class MdDialogContainer extends BasePortalHost implements OnDestroy {
private _ngZone: NgZone,
private _renderer: Renderer,
private _elementRef: ElementRef,
private _focusTrapFactory: FocusTrapFactory) {
private _focusTrapFactory: FocusTrapFactory,
@Optional() @Inject(DOCUMENT) private _document: any) {

super();
}
Expand All @@ -91,6 +95,7 @@ export class MdDialogContainer extends BasePortalHost implements OnDestroy {
throw new MdDialogContentAlreadyAttachedError();
}

this._savePreviouslyFocusedElement();
return this._portalHost.attachComponentPortal(portal);
}

Expand All @@ -103,6 +108,7 @@ export class MdDialogContainer extends BasePortalHost implements OnDestroy {
throw new MdDialogContentAlreadyAttachedError();
}

this._savePreviouslyFocusedElement();
return this._portalHost.attachTemplatePortal(portal);
}

Expand All @@ -118,10 +124,19 @@ export class MdDialogContainer extends BasePortalHost implements OnDestroy {
// If were to attempt to focus immediately, then the content of the dialog would not yet be
// ready in instances where change detection has to run first. To deal with this, we simply
// wait for the microtask queue to be empty.
this._elementFocusedBeforeDialogWasOpened = document.activeElement as HTMLElement;
this._focusTrap.focusFirstTabbableElementWhenReady();
}

/**
* Saves a reference to the element that was focused before the dialog was opened.
* @private
*/
private _savePreviouslyFocusedElement() {
if (this._document) {
this._elementFocusedBeforeDialogWasOpened = this._document.activeElement as HTMLElement;
}
}

/**
* Kicks off the leave animation.
* @docs-private
Expand Down

0 comments on commit 0098279

Please sign in to comment.