diff --git a/src/lib/form-field/form-field.ts b/src/lib/form-field/form-field.ts index e991283b2a4a..7f0a2920967c 100644 --- a/src/lib/form-field/form-field.ts +++ b/src/lib/form-field/form-field.ts @@ -444,7 +444,10 @@ export class MatFormField extends _MatFormFieldMixinBase * appearance. */ updateOutlineGap() { - if (this.appearance !== 'outline') { + const labelEl = this._label ? this._label.nativeElement : null; + + if (this.appearance !== 'outline' || !labelEl || !labelEl.children.length || + !labelEl.textContent.trim()) { return; } @@ -465,14 +468,14 @@ export class MatFormField extends _MatFormFieldMixinBase const containerStart = this._getStartEnd( this._connectionContainerRef.nativeElement.getBoundingClientRect()); - const labelStart = this._getStartEnd( - this._label.nativeElement.children[0].getBoundingClientRect()); + const labelStart = this._getStartEnd(labelEl.children[0].getBoundingClientRect()); let labelWidth = 0; - for (const child of this._label.nativeElement.children) { + + for (const child of labelEl.children) { labelWidth += child.offsetWidth; } startWidth = labelStart - containerStart - outlineGapPadding; - gapWidth = labelWidth * floatingLabelScale + outlineGapPadding * 2; + gapWidth = labelWidth > 0 ? labelWidth * floatingLabelScale + outlineGapPadding * 2 : 0; } for (let i = 0; i < startEls.length; i++) { diff --git a/src/lib/input/input.spec.ts b/src/lib/input/input.spec.ts index bb34d05d7578..c947618ebd2f 100644 --- a/src/lib/input/input.spec.ts +++ b/src/lib/input/input.spec.ts @@ -1151,6 +1151,25 @@ describe('MatInput with appearance', () => { expect(parseInt(outlineStart.style.width)).toBeGreaterThan(0); expect(parseInt(outlineGap.style.width)).toBeGreaterThan(0); })); + + it('should not set an outline gap if the label is empty', fakeAsync(() => { + fixture.destroy(); + TestBed.resetTestingModule(); + + const outlineFixture = createComponent(MatInputWithAppearanceAndLabel); + + outlineFixture.componentInstance.labelContent = ''; + outlineFixture.detectChanges(); + outlineFixture.componentInstance.appearance = 'outline'; + outlineFixture.detectChanges(); + flush(); + outlineFixture.detectChanges(); + + const outlineGap = outlineFixture.nativeElement.querySelector('.mat-form-field-outline-gap'); + + expect(parseInt(outlineGap.style.width)).toBeFalsy(); + })); + }); describe('MatFormField default options', () => { @@ -1594,13 +1613,14 @@ class MatInputWithAppearance { @Component({ template: ` - Label + {{labelContent}} ` }) class MatInputWithAppearanceAndLabel { appearance: MatFormFieldAppearance; + labelContent = 'Label'; } @Component({