6
6
Renderer ,
7
7
ElementRef ,
8
8
EventEmitter ,
9
+ Inject ,
10
+ Optional ,
9
11
} from '@angular/core' ;
10
12
import {
11
13
animate ,
@@ -15,6 +17,7 @@ import {
15
17
transition ,
16
18
AnimationEvent ,
17
19
} from '@angular/animations' ;
20
+ import { DOCUMENT } from '@angular/platform-browser' ;
18
21
import { BasePortalHost , ComponentPortal , PortalHostDirective , TemplatePortal } from '../core' ;
19
22
import { MdDialogConfig } from './dialog-config' ;
20
23
import { MdDialogContentAlreadyAttachedError } from './dialog-errors' ;
@@ -57,6 +60,9 @@ export class MdDialogContainer extends BasePortalHost {
57
60
/** Element that was focused before the dialog was opened. Save this to restore upon close. */
58
61
private _elementFocusedBeforeDialogWasOpened : HTMLElement = null ;
59
62
63
+ /** Reference to the global document object. */
64
+ private _document : Document ;
65
+
60
66
/** The dialog configuration. */
61
67
dialogConfig : MdDialogConfig ;
62
68
@@ -69,9 +75,11 @@ export class MdDialogContainer extends BasePortalHost {
69
75
constructor (
70
76
private _renderer : Renderer ,
71
77
private _elementRef : ElementRef ,
72
- private _focusTrapFactory : FocusTrapFactory ) {
78
+ private _focusTrapFactory : FocusTrapFactory ,
79
+ @Optional ( ) @Inject ( DOCUMENT ) _document : any ) {
73
80
74
81
super ( ) ;
82
+ this . _document = _document ;
75
83
}
76
84
77
85
/**
@@ -83,6 +91,7 @@ export class MdDialogContainer extends BasePortalHost {
83
91
throw new MdDialogContentAlreadyAttachedError ( ) ;
84
92
}
85
93
94
+ this . _savePreviouslyFocusedElement ( ) ;
86
95
return this . _portalHost . attachComponentPortal ( portal ) ;
87
96
}
88
97
@@ -95,6 +104,7 @@ export class MdDialogContainer extends BasePortalHost {
95
104
throw new MdDialogContentAlreadyAttachedError ( ) ;
96
105
}
97
106
107
+ this . _savePreviouslyFocusedElement ( ) ;
98
108
return this . _portalHost . attachTemplatePortal ( portal ) ;
99
109
}
100
110
@@ -109,10 +119,18 @@ export class MdDialogContainer extends BasePortalHost {
109
119
// If were to attempt to focus immediately, then the content of the dialog would not yet be
110
120
// ready in instances where change detection has to run first. To deal with this, we simply
111
121
// wait for the microtask queue to be empty.
112
- this . _elementFocusedBeforeDialogWasOpened = document . activeElement as HTMLElement ;
113
122
this . _focusTrap . focusFirstTabbableElementWhenReady ( ) ;
114
123
}
115
124
125
+ /**
126
+ * Saves a reference to the element that was focused before the dialog was opened.
127
+ */
128
+ private _savePreviouslyFocusedElement ( ) {
129
+ if ( this . _document ) {
130
+ this . _elementFocusedBeforeDialogWasOpened = this . _document . activeElement as HTMLElement ;
131
+ }
132
+ }
133
+
116
134
/**
117
135
* Callback, invoked whenever an animation on the host completes.
118
136
* @docs -private
0 commit comments