@@ -330,11 +330,16 @@ export class CdkConnectedOverlay implements OnDestroy, OnChanges {
330
330
private _attachOverlay ( ) {
331
331
if ( ! this . _overlayRef ) {
332
332
this . _createOverlay ( ) ;
333
+
334
+ this . _overlayRef ! . keydownEvents ( ) . subscribe ( ( event : KeyboardEvent ) => {
335
+ if ( event . keyCode === ESCAPE ) {
336
+ this . _detachOverlay ( ) ;
337
+ }
338
+ } ) ;
333
339
}
334
340
335
341
this . _position . withDirection ( this . dir ) ;
336
342
this . _overlayRef . setDirection ( this . dir ) ;
337
- this . _document . addEventListener ( 'keydown' , this . _escapeListener ) ;
338
343
339
344
if ( ! this . _overlayRef . hasAttached ( ) ) {
340
345
this . _overlayRef . attach ( this . _templatePortal ) ;
@@ -356,7 +361,6 @@ export class CdkConnectedOverlay implements OnDestroy, OnChanges {
356
361
}
357
362
358
363
this . _backdropSubscription . unsubscribe ( ) ;
359
- this . _document . removeEventListener ( 'keydown' , this . _escapeListener ) ;
360
364
}
361
365
362
366
/** Destroys the overlay created by this directive. */
@@ -367,13 +371,5 @@ export class CdkConnectedOverlay implements OnDestroy, OnChanges {
367
371
368
372
this . _backdropSubscription . unsubscribe ( ) ;
369
373
this . _positionSubscription . unsubscribe ( ) ;
370
- this . _document . removeEventListener ( 'keydown' , this . _escapeListener ) ;
371
- }
372
-
373
- /** Event listener that will close the overlay when the user presses escape. */
374
- private _escapeListener = ( event : KeyboardEvent ) => {
375
- if ( event . keyCode === ESCAPE ) {
376
- this . _detachOverlay ( ) ;
377
- }
378
374
}
379
375
}
0 commit comments