Skip to content

Commit febc0eb

Browse files
authoredApr 2, 2025··
Add a null check to autocomplete options (#30734)
* fix a bug with null options * Add a test
1 parent dd69023 commit febc0eb

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
@@ -625,12 +625,12 @@ export class MatAutocompleteTrigger
625625
{injector: this._environmentInjector},
626626
);
627627
});
628-
const optionChanges = this.autocomplete.options.changes.pipe(
628+
const optionChanges = this.autocomplete.options?.changes.pipe(
629629
tap(() => this._positionStrategy.reapplyLastPosition()),
630630
// Defer emitting to the stream until the next tick, because changing
631631
// bindings in here will cause "changed after checked" errors.
632632
delay(0),
633-
);
633+
) ?? observableOf();
634634

635635
// When the options are initially rendered, and when the option list changes...
636636
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
@@ -307,7 +307,7 @@ export class MatAutocomplete implements AfterContentInit, OnDestroy {
307307

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

0 commit comments

Comments
 (0)
Please sign in to comment.