Skip to content

Commit a731c68

Browse files
crisbetommalerba
authored andcommitted
fix(form-field): native select label floating incorrectly when invalid value is set (#14263)
Fixes the label for a form field with a native select floating when it isn't supposed to, if a value that isn't in the options list is assigned.
1 parent c759cdb commit a731c68

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

src/lib/input/input.spec.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -643,6 +643,21 @@ describe('MatInput without forms', () => {
643643
expect(formFieldEl.classList).toContain('mat-form-field-should-float');
644644
}));
645645

646+
it('should not float the label if the selectedIndex is negative', fakeAsync(() => {
647+
const fixture = createComponent(MatInputSelect);
648+
fixture.detectChanges();
649+
650+
const formFieldEl = fixture.debugElement.query(By.css('.mat-form-field')).nativeElement;
651+
const selectEl: HTMLSelectElement = formFieldEl.querySelector('select');
652+
653+
expect(formFieldEl.classList).toContain('mat-form-field-should-float');
654+
655+
selectEl.selectedIndex = -1;
656+
fixture.detectChanges();
657+
658+
expect(formFieldEl.classList).not.toContain('mat-form-field-should-float');
659+
}));
660+
646661
it('should not float labels when select has no value, no option label, ' +
647662
'no option innerHtml', fakeAsync(() => {
648663
const fixture = createComponent(MatInputSelectWithNoLabelNoValue);

src/lib/input/input.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -385,8 +385,10 @@ export class MatInput extends _MatInputMixinBase implements MatFormFieldControl<
385385
const selectElement = this._elementRef.nativeElement as HTMLSelectElement;
386386
const firstOption: HTMLOptionElement | undefined = selectElement.options[0];
387387

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

0 commit comments

Comments
 (0)