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.
This commit is contained in:
Kristiyan Kostadinov
2018-11-27 16:45:18 +01:00
committed by Jeremy Elbourn
parent db7491c8b0
commit d5352d3690
2 changed files with 20 additions and 3 deletions
+14
View File
@@ -671,6 +671,11 @@ describe('MatInput without forms', () => {
expect(formFieldEl.classList).toContain('mat-form-field-should-float');
}));
it('should not throw if a native select does not have options', fakeAsync(() => {
const fixture = createComponent(MatInputSelectWithoutOptions);
expect(() => fixture.detectChanges()).not.toThrow();
}));
it('should never float the label when floatLabel is set to false', fakeAsync(() => {
let fixture = createComponent(MatInputWithDynamicLabel);
@@ -1933,6 +1938,15 @@ class MatInputSelectWithInnerHtml {}
})
class MatInputWithCustomAccessor {}
@Component({
template: `
<mat-form-field>
<select matNativeControl>
</select>
</mat-form-field>`
})
class MatInputSelectWithoutOptions {}
/** Custom component that never has a value. Used for testing the `MAT_INPUT_VALUE_ACCESSOR`. */
@Directive({
+6 -3
View File
@@ -383,9 +383,10 @@ export class MatInput extends _MatInputMixinBase implements MatFormFieldControl<
// a non-empty display value. For a `<select multiple>`, the label *always* floats to avoid
// overlapping the label with the options.
const selectElement = this._elementRef.nativeElement as HTMLSelectElement;
const firstOption: HTMLOptionElement | undefined = selectElement.options[0];
return selectElement.multiple || !this.empty || !!selectElement.options[0].label ||
this.focused;
return selectElement.multiple || !this.empty || this.focused ||
!!(firstOption && firstOption.label);
} else {
return this.focused || !this.empty;
}
@@ -395,7 +396,9 @@ export class MatInput extends _MatInputMixinBase implements MatFormFieldControl<
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
setDescribedByIds(ids: string[]) { this._ariaDescribedby = ids.join(' '); }
setDescribedByIds(ids: string[]) {
this._ariaDescribedby = ids.join(' ');
}
/**
* Implemented as part of MatFormFieldControl.