@@ -3,6 +3,7 @@ import {Observable} from 'rxjs/Observable';
33import { Subject } from 'rxjs/Subject' ;
44import { Overlay , OverlayRef , ComponentType , OverlayState , ComponentPortal } from '../core' ;
55import { extendObject } from '../core/util/object-extend' ;
6+ import { ESCAPE } from '../core/keyboard/keycodes' ;
67import { DialogInjector } from './dialog-injector' ;
78import { MdDialogConfig } from './dialog-config' ;
89import { MdDialogRef } from './dialog-ref' ;
@@ -22,6 +23,7 @@ export class MdDialog {
2223 private _openDialogsAtThisLevel : MdDialogRef < any > [ ] = [ ] ;
2324 private _afterAllClosedAtThisLevel = new Subject < void > ( ) ;
2425 private _afterOpenAtThisLevel = new Subject < MdDialogRef < any > > ( ) ;
26+ private _boundKeydown = this . _handleKeydown . bind ( this ) ;
2527
2628 /** Keeps track of the currently-open dialogs. */
2729 get _openDialogs ( ) : MdDialogRef < any > [ ] {
@@ -65,6 +67,10 @@ export class MdDialog {
6567 let dialogRef =
6668 this . _attachDialogContent ( componentOrTemplateRef , dialogContainer , overlayRef , config ) ;
6769
70+ if ( ! this . _openDialogs . length && ! this . _parentDialog ) {
71+ document . addEventListener ( 'keydown' , this . _boundKeydown ) ;
72+ }
73+
6874 this . _openDialogs . push ( dialogRef ) ;
6975 dialogRef . afterClosed ( ) . subscribe ( ( ) => this . _removeOpenDialog ( dialogRef ) ) ;
7076 this . _afterOpen . next ( dialogRef ) ;
@@ -129,7 +135,7 @@ export class MdDialog {
129135 config ?: MdDialogConfig ) : MdDialogRef < T > {
130136 // Create a reference to the dialog we're creating in order to give the user a handle
131137 // to modify and close it.
132- let dialogRef = < MdDialogRef < T > > new MdDialogRef ( overlayRef ) ;
138+ let dialogRef = < MdDialogRef < T > > new MdDialogRef ( overlayRef , config ) ;
133139
134140 if ( ! config . disableClose ) {
135141 // When the dialog backdrop is clicked, we want to close it.
@@ -199,9 +205,22 @@ export class MdDialog {
199205 // no open dialogs are left, call next on afterAllClosed Subject
200206 if ( ! this . _openDialogs . length ) {
201207 this . _afterAllClosed . next ( ) ;
208+ document . removeEventListener ( 'keydown' , this . _boundKeydown ) ;
202209 }
203210 }
204211 }
212+
213+ /**
214+ * Handles global key presses while there are open dialogs. Closes the
215+ * top dialog when the user presses escape.
216+ */
217+ private _handleKeydown ( event : KeyboardEvent ) : void {
218+ let topDialog = this . _openDialogs [ this . _openDialogs . length - 1 ] ;
219+
220+ if ( event . keyCode === ESCAPE && topDialog && ! topDialog . config . disableClose ) {
221+ topDialog . close ( ) ;
222+ }
223+ }
205224}
206225
207226/**
0 commit comments