Skip to content

Commit 0ef75ea

Browse files
crisbetojelbourn
authored andcommitted
fix(form-field): error when native select has no options (#14102)
Fixes an error being thrown when there's a native `select` without any options inside a `mat-form-field`. Fixes #14101.
1 parent 4acecd7 commit 0ef75ea

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed

src/lib/input/input.spec.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -671,6 +671,11 @@ describe('MatInput without forms', () => {
671671
expect(formFieldEl.classList).toContain('mat-form-field-should-float');
672672
}));
673673

674+
it('should not throw if a native select does not have options', fakeAsync(() => {
675+
const fixture = createComponent(MatInputSelectWithoutOptions);
676+
expect(() => fixture.detectChanges()).not.toThrow();
677+
}));
678+
674679
it('should never float the label when floatLabel is set to false', fakeAsync(() => {
675680
let fixture = createComponent(MatInputWithDynamicLabel);
676681

@@ -1933,6 +1938,15 @@ class MatInputSelectWithInnerHtml {}
19331938
})
19341939
class MatInputWithCustomAccessor {}
19351940

1941+
@Component({
1942+
template: `
1943+
<mat-form-field>
1944+
<select matNativeControl>
1945+
</select>
1946+
</mat-form-field>`
1947+
})
1948+
class MatInputSelectWithoutOptions {}
1949+
19361950

19371951
/** Custom component that never has a value. Used for testing the `MAT_INPUT_VALUE_ACCESSOR`. */
19381952
@Directive({

src/lib/input/input.ts

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -383,9 +383,10 @@ export class MatInput extends _MatInputMixinBase implements MatFormFieldControl<
383383
// a non-empty display value. For a `<select multiple>`, the label *always* floats to avoid
384384
// overlapping the label with the options.
385385
const selectElement = this._elementRef.nativeElement as HTMLSelectElement;
386+
const firstOption: HTMLOptionElement | undefined = selectElement.options[0];
386387

387-
return selectElement.multiple || !this.empty || !!selectElement.options[0].label ||
388-
this.focused;
388+
return selectElement.multiple || !this.empty || this.focused ||
389+
!!(firstOption && firstOption.label);
389390
} else {
390391
return this.focused || !this.empty;
391392
}
@@ -395,7 +396,9 @@ export class MatInput extends _MatInputMixinBase implements MatFormFieldControl<
395396
* Implemented as part of MatFormFieldControl.
396397
* @docs-private
397398
*/
398-
setDescribedByIds(ids: string[]) { this._ariaDescribedby = ids.join(' '); }
399+
setDescribedByIds(ids: string[]) {
400+
this._ariaDescribedby = ids.join(' ');
401+
}
399402

400403
/**
401404
* Implemented as part of MatFormFieldControl.

0 commit comments

Comments
 (0)