Skip to content

Commit 2b05106

Browse files
crisbetojelbourn
authored andcommitted
fix(autocomplete): error when closing from a destroyed view (#7365)
Fixes an error that was being thrown, because the autocomplete tries to run change detection on a destroyed view. Fixes #7315.
1 parent 8298db1 commit 2b05106

File tree

1 file changed

+11
-5
lines changed

1 file changed

+11
-5
lines changed

src/lib/autocomplete/autocomplete-trigger.ts

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,7 @@ export class MatAutocompleteTrigger implements ControlValueAccessor, OnDestroy {
119119
private _overlayRef: OverlayRef | null;
120120
private _portal: TemplatePortal;
121121
private _panelOpen: boolean = false;
122+
private _componentDestroyed = false;
122123

123124
/** Strategy that is used to position the panel. */
124125
private _positionStrategy: ConnectedPositionStrategy;
@@ -151,6 +152,7 @@ export class MatAutocompleteTrigger implements ControlValueAccessor, OnDestroy {
151152
@Optional() @Inject(DOCUMENT) private _document: any) {}
152153

153154
ngOnDestroy() {
155+
this._componentDestroyed = true;
154156
this._destroyPanel();
155157
this._closeKeyEventStream.complete();
156158
}
@@ -178,11 +180,15 @@ export class MatAutocompleteTrigger implements ControlValueAccessor, OnDestroy {
178180
this._closingActionsSubscription.unsubscribe();
179181
}
180182

181-
// We need to trigger change detection manually, because
182-
// `fromEvent` doesn't seem to do it at the proper time.
183-
// This ensures that the label is reset when the
184-
// user clicks outside.
185-
this._changeDetectorRef.detectChanges();
183+
// Note that in some cases this can end up being called after the component is destroyed.
184+
// Add a check to ensure that we don't try to run change detection on a destroyed view.
185+
if (!this._componentDestroyed) {
186+
// We need to trigger change detection manually, because
187+
// `fromEvent` doesn't seem to do it at the proper time.
188+
// This ensures that the label is reset when the
189+
// user clicks outside.
190+
this._changeDetectorRef.detectChanges();
191+
}
186192
}
187193
}
188194

0 commit comments

Comments
 (0)