@@ -36,6 +36,10 @@ export class FocusTrap {
36
36
private _endAnchor : HTMLElement | null ;
37
37
private _hasAttached = false ;
38
38
39
+ // Event listeners for the anchors. Need to be regular functions so that we can unbind them later.
40
+ private _startAnchorListener = ( ) => this . focusLastTabbableElement ( ) ;
41
+ private _endAnchorListener = ( ) => this . focusFirstTabbableElement ( ) ;
42
+
39
43
/** Whether the focus trap is active. */
40
44
get enabled ( ) : boolean { return this . _enabled ; }
41
45
set enabled ( value : boolean ) {
@@ -62,12 +66,23 @@ export class FocusTrap {
62
66
63
67
/** Destroys the focus trap by cleaning up the anchors. */
64
68
destroy ( ) {
65
- if ( this . _startAnchor && this . _startAnchor . parentNode ) {
66
- this . _startAnchor . parentNode . removeChild ( this . _startAnchor ) ;
69
+ const startAnchor = this . _startAnchor ;
70
+ const endAnchor = this . _endAnchor ;
71
+
72
+ if ( startAnchor ) {
73
+ startAnchor . removeEventListener ( 'focus' , this . _startAnchorListener ) ;
74
+
75
+ if ( startAnchor . parentNode ) {
76
+ startAnchor . parentNode . removeChild ( startAnchor ) ;
77
+ }
67
78
}
68
79
69
- if ( this . _endAnchor && this . _endAnchor . parentNode ) {
70
- this . _endAnchor . parentNode . removeChild ( this . _endAnchor ) ;
80
+ if ( endAnchor ) {
81
+ endAnchor . removeEventListener ( 'focus' , this . _endAnchorListener ) ;
82
+
83
+ if ( endAnchor . parentNode ) {
84
+ endAnchor . parentNode . removeChild ( endAnchor ) ;
85
+ }
71
86
}
72
87
73
88
this . _startAnchor = this . _endAnchor = null ;
@@ -88,12 +103,12 @@ export class FocusTrap {
88
103
this . _ngZone . runOutsideAngular ( ( ) => {
89
104
if ( ! this . _startAnchor ) {
90
105
this . _startAnchor = this . _createAnchor ( ) ;
91
- this . _startAnchor ! . addEventListener ( 'focus' , ( ) => this . focusLastTabbableElement ( ) ) ;
106
+ this . _startAnchor ! . addEventListener ( 'focus' , this . _startAnchorListener ) ;
92
107
}
93
108
94
109
if ( ! this . _endAnchor ) {
95
110
this . _endAnchor = this . _createAnchor ( ) ;
96
- this . _endAnchor ! . addEventListener ( 'focus' , ( ) => this . focusFirstTabbableElement ( ) ) ;
111
+ this . _endAnchor ! . addEventListener ( 'focus' , this . _endAnchorListener ) ;
97
112
}
98
113
} ) ;
99
114
0 commit comments