diff --git a/src/lib/select/select.spec.ts b/src/lib/select/select.spec.ts index a58f331646b..9f2732d6a48 100644 --- a/src/lib/select/select.spec.ts +++ b/src/lib/select/select.spec.ts @@ -2511,6 +2511,11 @@ describe('MatSelect', () => { expect(label.textContent).toContain('azziP', 'Expected the displayed text to be "Pizza" in reverse.'); })); + + it('should not throw when attempting to open too early', () => { + const fixture = TestBed.createComponent(BasicSelect); + expect(() => fixture.componentInstance.select.open()).not.toThrow(); + }); }); describe('change event', () => { diff --git a/src/lib/select/select.ts b/src/lib/select/select.ts index 0e4e3017b92..5688af37e37 100644 --- a/src/lib/select/select.ts +++ b/src/lib/select/select.ts @@ -515,7 +515,7 @@ export class MatSelect extends _MatSelectMixinBase implements AfterContentInit, /** Opens the overlay panel. */ open(): void { - if (this.disabled || !this.options.length) { + if (this.disabled || !this.options || !this.options.length) { return; } @@ -605,7 +605,7 @@ export class MatSelect extends _MatSelectMixinBase implements AfterContentInit, /** The value displayed in the trigger. */ get triggerValue(): string { - if (!this._selectionModel || this._selectionModel.isEmpty()) { + if (this.empty) { return ''; } @@ -912,10 +912,12 @@ export class MatSelect extends _MatSelectMixinBase implements AfterContentInit, * the first item instead. */ private _highlightCorrectOption(): void { - if (this._selectionModel.isEmpty()) { - this._keyManager.setFirstItemActive(); - } else { - this._keyManager.setActiveItem(this._getOptionIndex(this._selectionModel.selected[0])!); + if (this._keyManager) { + if (this.empty) { + this._keyManager.setFirstItemActive(); + } else { + this._keyManager.setActiveItem(this._getOptionIndex(this._selectionModel.selected[0])!); + } } }