Skip to content

Commit 2cee7d7

Browse files
committed
fix(autocomplete): error when closing from a destroyed view
Fixes an error that was being thrown, because the autocomplete tries to run change detection on a destroyed view. Fixes #7315.
1 parent af44b9d commit 2cee7d7

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
@@ -118,6 +118,7 @@ export class MatAutocompleteTrigger implements ControlValueAccessor, OnDestroy {
118118
private _overlayRef: OverlayRef | null;
119119
private _portal: TemplatePortal<any>;
120120
private _panelOpen: boolean = false;
121+
private _componentDestroyed = false;
121122

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

152153
ngOnDestroy() {
154+
this._componentDestroyed = true;
153155
this._destroyPanel();
154156
this._escapeEventStream.complete();
155157
}
@@ -177,11 +179,15 @@ export class MatAutocompleteTrigger implements ControlValueAccessor, OnDestroy {
177179
this._closingActionsSubscription.unsubscribe();
178180
}
179181

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

0 commit comments

Comments
 (0)