diff --git a/src/material/autocomplete/autocomplete-trigger.ts b/src/material/autocomplete/autocomplete-trigger.ts index c7e4fd457934..b8e2eb7c9bc2 100644 --- a/src/material/autocomplete/autocomplete-trigger.ts +++ b/src/material/autocomplete/autocomplete-trigger.ts @@ -625,12 +625,12 @@ export class MatAutocompleteTrigger {injector: this._environmentInjector}, ); }); - const optionChanges = this.autocomplete.options.changes.pipe( + const optionChanges = this.autocomplete.options?.changes.pipe( tap(() => this._positionStrategy.reapplyLastPosition()), // Defer emitting to the stream until the next tick, because changing // bindings in here will cause "changed after checked" errors. delay(0), - ); + ) ?? observableOf(); // When the options are initially rendered, and when the option list changes... return ( diff --git a/src/material/autocomplete/autocomplete.spec.ts b/src/material/autocomplete/autocomplete.spec.ts index 9a27005487f9..112899f57124 100644 --- a/src/material/autocomplete/autocomplete.spec.ts +++ b/src/material/autocomplete/autocomplete.spec.ts @@ -3252,6 +3252,17 @@ describe('MatAutocomplete', () => { }); }); + it('should not throw errors when closing without options', fakeAsync(() => { + const fixture = createComponent(AutocompleteWithoutOptions); + const trigger = fixture.componentInstance.trigger; + + trigger.openPanel(); + fixture.detectChanges(); + fixture.destroy(); + + expect(() => trigger.closePanel()).not.toThrow(); + })); + describe('automatically selecting the active option', () => { let fixture: ComponentFixture; @@ -4496,3 +4507,20 @@ class AutocompleteInsideAModal { @ViewChildren(MatOption) options: QueryList; @ViewChild('modal') modal: ElementRef; } + +@Component({ + selector: 'autocomplete-without-options', + template: ` + + + + + + + `, + standalone: false, +}) +class AutocompleteWithoutOptions { + @ViewChild(MatAutocompleteTrigger, { static: true }) trigger: MatAutocompleteTrigger; +} + diff --git a/src/material/autocomplete/autocomplete.ts b/src/material/autocomplete/autocomplete.ts index 475023b30661..54078571d1f0 100644 --- a/src/material/autocomplete/autocomplete.ts +++ b/src/material/autocomplete/autocomplete.ts @@ -307,7 +307,7 @@ export class MatAutocomplete implements AfterContentInit, OnDestroy { /** Panel should hide itself when the option list is empty. */ _setVisibility() { - this.showPanel = !!this.options.length; + this.showPanel = !!this.options?.length; this._changeDetectorRef.markForCheck(); }