Skip to content

Commit

Permalink
fix(form-field): error when native select has no options (#14102)
Browse files Browse the repository at this point in the history
Fixes an error being thrown when there's a native `select` without any options inside a `mat-form-field`.

Fixes #14101.
  • Loading branch information
crisbeto authored and jelbourn committed Dec 3, 2018
1 parent 4acecd7 commit 0ef75ea
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
14 changes: 14 additions & 0 deletions src/lib/input/input.spec.ts
Expand Up @@ -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);

Expand Down Expand Up @@ -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({
Expand Down
9 changes: 6 additions & 3 deletions src/lib/input/input.ts
Expand Up @@ -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;
}
Expand All @@ -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.
Expand Down

0 comments on commit 0ef75ea

Please sign in to comment.