diff --git a/src/lib/autocomplete/autocomplete-trigger.ts b/src/lib/autocomplete/autocomplete-trigger.ts
index 776b87117479..986e51bf5673 100644
--- a/src/lib/autocomplete/autocomplete-trigger.ts
+++ b/src/lib/autocomplete/autocomplete-trigger.ts
@@ -569,8 +569,15 @@ export class MatAutocompleteTrigger implements ControlValueAccessor, OnDestroy {
throw getMatAutocompleteMissingPanelError();
}
- if (!this._overlayRef) {
+ if (!this._portal || this._portal.templateRef !== this.autocomplete.template) {
this._portal = new TemplatePortal(this.autocomplete.template, this._viewContainerRef);
+
+ if (this._overlayRef && this._overlayRef.hasAttached()) {
+ this._overlayRef.detach();
+ }
+ }
+
+ if (!this._overlayRef) {
this._overlayRef = this._overlay.create(this._getOverlayConfig());
// Use the `keydownEvents` in order to take advantage of
diff --git a/src/lib/autocomplete/autocomplete.spec.ts b/src/lib/autocomplete/autocomplete.spec.ts
index d03b7bc34729..b2b1958b9868 100644
--- a/src/lib/autocomplete/autocomplete.spec.ts
+++ b/src/lib/autocomplete/autocomplete.spec.ts
@@ -2221,6 +2221,38 @@ describe('MatAutocomplete', () => {
expect(formControl.value).toBe('Cal', 'Expected new value to be propagated to model');
}));
+ it('should work when dynamically changing the autocomplete', () => {
+ const fixture = createComponent(DynamicallyChangingAutocomplete);
+ fixture.detectChanges();
+ const input = fixture.debugElement.query(By.css('input')).nativeElement;
+
+ dispatchFakeEvent(input, 'focusin');
+ fixture.detectChanges();
+
+ expect(overlayContainerElement.textContent).toContain('First',
+ `Expected panel to display the option of the first autocomplete.`);
+ expect(overlayContainerElement.textContent).not.toContain('Second',
+ `Expected panel to not display the option of the second autocomplete.`);
+
+ // close overlay
+ dispatchFakeEvent(document, 'click');
+ fixture.detectChanges();
+
+ // Switch to second autocomplete
+ fixture.componentInstance.selected = 1;
+ fixture.detectChanges();
+
+ // reopen agian
+ dispatchFakeEvent(input, 'focusin');
+ fixture.detectChanges();
+
+ expect(overlayContainerElement.textContent).not.toContain('First',
+ `Expected panel to not display the option of the first autocomplete.`);
+ expect(overlayContainerElement.textContent).toContain('Second',
+ `Expected panel to display the option of the second autocomplete.`);
+
+ });
+
});
@Component({
@@ -2607,3 +2639,19 @@ class AutocompleteWithNativeAutocompleteAttribute {
})
class InputWithoutAutocompleteAndDisabled {
}
+
+@Component({
+ template: `
+
+
+ First
+
+
+
+ Second
+
+ `,
+})
+class DynamicallyChangingAutocomplete {
+ selected = 0;
+}