From 2cee7d7335085d314cd264c11eef06296881c182 Mon Sep 17 00:00:00 2001 From: crisbeto Date: Wed, 27 Sep 2017 21:05:44 +0200 Subject: [PATCH] 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. --- src/lib/autocomplete/autocomplete-trigger.ts | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/src/lib/autocomplete/autocomplete-trigger.ts b/src/lib/autocomplete/autocomplete-trigger.ts index 9ee22496d39c..ecbab0e01033 100644 --- a/src/lib/autocomplete/autocomplete-trigger.ts +++ b/src/lib/autocomplete/autocomplete-trigger.ts @@ -118,6 +118,7 @@ export class MatAutocompleteTrigger implements ControlValueAccessor, OnDestroy { private _overlayRef: OverlayRef | null; private _portal: TemplatePortal; private _panelOpen: boolean = false; + private _componentDestroyed = false; /** Strategy that is used to position the panel. */ private _positionStrategy: ConnectedPositionStrategy; @@ -150,6 +151,7 @@ export class MatAutocompleteTrigger implements ControlValueAccessor, OnDestroy { @Optional() @Inject(DOCUMENT) private _document: any) {} ngOnDestroy() { + this._componentDestroyed = true; this._destroyPanel(); this._escapeEventStream.complete(); } @@ -177,11 +179,15 @@ export class MatAutocompleteTrigger implements ControlValueAccessor, OnDestroy { this._closingActionsSubscription.unsubscribe(); } - // We need to trigger change detection manually, because - // `fromEvent` doesn't seem to do it at the proper time. - // This ensures that the label is reset when the - // user clicks outside. - this._changeDetectorRef.detectChanges(); + // Note that in some cases this can end up being called after the component is destroyed. + // Add a check to ensure that we don't try to run change detection on a destroyed view. + if (!this._componentDestroyed) { + // We need to trigger change detection manually, because + // `fromEvent` doesn't seem to do it at the proper time. + // This ensures that the label is reset when the + // user clicks outside. + this._changeDetectorRef.detectChanges(); + } } }