Skip to content

fix(form-field): native select label floating incorrectly when invalid value is set #14263

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
Dec 4, 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
15 changes: 15 additions & 0 deletions src/lib/input/input.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -643,6 +643,21 @@ describe('MatInput without forms', () => {
expect(formFieldEl.classList).toContain('mat-form-field-should-float');
}));

it('should not float the label if the selectedIndex is negative', fakeAsync(() => {
const fixture = createComponent(MatInputSelect);
fixture.detectChanges();

const formFieldEl = fixture.debugElement.query(By.css('.mat-form-field')).nativeElement;
const selectEl: HTMLSelectElement = formFieldEl.querySelector('select');

expect(formFieldEl.classList).toContain('mat-form-field-should-float');

selectEl.selectedIndex = -1;
fixture.detectChanges();

expect(formFieldEl.classList).not.toContain('mat-form-field-should-float');
}));

it('should not float labels when select has no value, no option label, ' +
'no option innerHtml', fakeAsync(() => {
const fixture = createComponent(MatInputSelectWithNoLabelNoValue);
Expand Down
6 changes: 4 additions & 2 deletions src/lib/input/input.ts
Original file line number Diff line number Diff line change
Expand Up @@ -385,8 +385,10 @@ export class MatInput extends _MatInputMixinBase implements MatFormFieldControl<
const selectElement = this._elementRef.nativeElement as HTMLSelectElement;
const firstOption: HTMLOptionElement | undefined = selectElement.options[0];

return selectElement.multiple || !this.empty || this.focused ||
!!(firstOption && firstOption.label);
// On most browsers the `selectedIndex` will always be 0, however on IE and Edge it'll be
// -1 if the `value` is set to something, that isn't in the list of options, at a later point.
return this.focused || selectElement.multiple || !this.empty ||
!!(selectElement.selectedIndex > -1 && firstOption && firstOption.label);
} else {
return this.focused || !this.empty;
}
Expand Down