Skip to content

Commit d8aafee

Browse files
rileyajonesmmalerba
authored andcommitted
Add a null check to autocomplete options (#30734)
* fix a bug with null options * Add a test (cherry picked from commit febc0eb)
1 parent bc99b42 commit d8aafee

File tree

3 files changed

+31
-3
lines changed

3 files changed

+31
-3
lines changed

src/material/autocomplete/autocomplete-trigger.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -622,12 +622,12 @@ export class MatAutocompleteTrigger
622622
{injector: this._environmentInjector},
623623
);
624624
});
625-
const optionChanges = this.autocomplete.options.changes.pipe(
625+
const optionChanges = this.autocomplete.options?.changes.pipe(
626626
tap(() => this._positionStrategy.reapplyLastPosition()),
627627
// Defer emitting to the stream until the next tick, because changing
628628
// bindings in here will cause "changed after checked" errors.
629629
delay(0),
630-
);
630+
) ?? observableOf();
631631

632632
// When the options are initially rendered, and when the option list changes...
633633
return (

src/material/autocomplete/autocomplete.spec.ts

+28
Original file line numberDiff line numberDiff line change
@@ -3252,6 +3252,17 @@ describe('MatAutocomplete', () => {
32523252
});
32533253
});
32543254

3255+
it('should not throw errors when closing without options', fakeAsync(() => {
3256+
const fixture = createComponent(AutocompleteWithoutOptions);
3257+
const trigger = fixture.componentInstance.trigger;
3258+
3259+
trigger.openPanel();
3260+
fixture.detectChanges();
3261+
fixture.destroy();
3262+
3263+
expect(() => trigger.closePanel()).not.toThrow();
3264+
}));
3265+
32553266
describe('automatically selecting the active option', () => {
32563267
let fixture: ComponentFixture<SimpleAutocomplete>;
32573268

@@ -4496,3 +4507,20 @@ class AutocompleteInsideAModal {
44964507
@ViewChildren(MatOption) options: QueryList<MatOption>;
44974508
@ViewChild('modal') modal: ElementRef;
44984509
}
4510+
4511+
@Component({
4512+
selector: 'autocomplete-without-options',
4513+
template: `
4514+
<mat-form-field>
4515+
<input matInput [matAutocomplete]="auto">
4516+
</mat-form-field>
4517+
4518+
<mat-autocomplete #auto="matAutocomplete">
4519+
</mat-autocomplete>
4520+
`,
4521+
standalone: false,
4522+
})
4523+
class AutocompleteWithoutOptions {
4524+
@ViewChild(MatAutocompleteTrigger, { static: true }) trigger: MatAutocompleteTrigger;
4525+
}
4526+

src/material/autocomplete/autocomplete.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -308,7 +308,7 @@ export class MatAutocomplete implements AfterContentInit, OnDestroy {
308308

309309
/** Panel should hide itself when the option list is empty. */
310310
_setVisibility() {
311-
this.showPanel = !!this.options.length;
311+
this.showPanel = !!this.options?.length;
312312
this._changeDetectorRef.markForCheck();
313313
}
314314

0 commit comments

Comments
 (0)