Skip to content

fix(form-field): error when native select has no options #14102

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 27, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/lib/input/input.spec.ts
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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