From 77b6a6d860b5a0879fe584323bfb50df33d644d0 Mon Sep 17 00:00:00 2001 From: Kristiyan Kostadinov Date: Wed, 10 Mar 2021 23:22:57 +0100 Subject: [PATCH] fix(material/select): float label on focus if there's a placeholder (#19517) Historically we've only floated the `mat-select` label if a value is selected or the panel is open, because we wouldn't otherwise have anything to show. These changes make it so that we also float it on focus, if there's `placeholder` text that can be shown. This behavior is consistent with `MatInput`. Fixes #19514. (cherry picked from commit 7a972fbe38abc2401514dd2c24424faec645d2bb) --- src/material/select/select.spec.ts | 20 +++++++++++++++++--- src/material/select/select.ts | 2 +- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/src/material/select/select.spec.ts b/src/material/select/select.spec.ts index 14caf5e1878c..4c456a151067 100644 --- a/src/material/select/select.spec.ts +++ b/src/material/select/select.spec.ts @@ -2378,7 +2378,7 @@ describe('MatSelect', () => { .toBe(true, 'Label should be floating'); })); - it ('should default to global floating label type', fakeAsync(() => { + it('should default to global floating label type', fakeAsync(() => { fixture.destroy(); TestBed.resetTestingModule(); @@ -2409,6 +2409,19 @@ describe('MatSelect', () => { expect(formField.classList.contains('mat-form-field-should-float')) .toBe(true, 'Label should be floating'); })); + + it('should float the label on focus if it has a placeholder', fakeAsync(() => { + expect(fixture.componentInstance.placeholder).toBeTruthy(); + + fixture.componentInstance.floatLabel = 'auto'; + fixture.detectChanges(); + + dispatchFakeEvent(fixture.nativeElement.querySelector('.mat-select'), 'focus'); + fixture.detectChanges(); + + expect(formField.classList.contains('mat-form-field-should-float')) + .toBe(true, 'Label should be floating'); + })); }); describe('with a sibling component that throws an error', () => { @@ -4992,7 +5005,7 @@ class BasicSelectOnPushPreselected { selector: 'floating-label-select', template: ` - + {{ food.viewValue }} @@ -5002,6 +5015,7 @@ class BasicSelectOnPushPreselected { }) class FloatLabelSelect { floatLabel: FloatLabelType | null = 'auto'; + placeholder = 'Food I want to eat right now'; control = new FormControl(); foods: any[] = [ { value: 'steak-0', viewValue: 'Steak' }, @@ -5106,7 +5120,7 @@ class BasicSelectWithTheming { selector: 'reset-values-select', template: ` - + {{ food.viewValue }} diff --git a/src/material/select/select.ts b/src/material/select/select.ts index b11a9b27b71e..9c31ae533485 100644 --- a/src/material/select/select.ts +++ b/src/material/select/select.ts @@ -1090,7 +1090,7 @@ export abstract class _MatSelectBase extends _MatSelectMixinBase implements A * @docs-private */ get shouldLabelFloat(): boolean { - return this._panelOpen || !this.empty; + return this._panelOpen || !this.empty || (this._focused && !!this._placeholder); } static ngAcceptInputType_required: BooleanInput;