Skip to content

Commit 17bb9c3

Browse files
crisbetommalerba
authored andcommittedJan 4, 2019
fix(a11y): remove listeners when focus trap anchors are removed (#14629)
Fixes the `focus` event handlers, which retain a reference to the focus trap, not being cleaned up from the focus trap anchor elements on destroy.
1 parent 390310d commit 17bb9c3

File tree

1 file changed

+21
-6
lines changed

1 file changed

+21
-6
lines changed
 

‎src/cdk/a11y/focus-trap/focus-trap.ts

+21-6
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,10 @@ export class FocusTrap {
3636
private _endAnchor: HTMLElement | null;
3737
private _hasAttached = false;
3838

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+
3943
/** Whether the focus trap is active. */
4044
get enabled(): boolean { return this._enabled; }
4145
set enabled(value: boolean) {
@@ -62,12 +66,23 @@ export class FocusTrap {
6266

6367
/** Destroys the focus trap by cleaning up the anchors. */
6468
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+
}
6778
}
6879

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+
}
7186
}
7287

7388
this._startAnchor = this._endAnchor = null;
@@ -88,12 +103,12 @@ export class FocusTrap {
88103
this._ngZone.runOutsideAngular(() => {
89104
if (!this._startAnchor) {
90105
this._startAnchor = this._createAnchor();
91-
this._startAnchor!.addEventListener('focus', () => this.focusLastTabbableElement());
106+
this._startAnchor!.addEventListener('focus', this._startAnchorListener);
92107
}
93108

94109
if (!this._endAnchor) {
95110
this._endAnchor = this._createAnchor();
96-
this._endAnchor!.addEventListener('focus', () => this.focusFirstTabbableElement());
111+
this._endAnchor!.addEventListener('focus', this._endAnchorListener);
97112
}
98113
});
99114

0 commit comments

Comments
 (0)
Please sign in to comment.