From 1055720fe19960837a02b3521232ac9106c7f8ad Mon Sep 17 00:00:00 2001 From: Paul Gschwendtner Date: Mon, 5 Jun 2017 23:46:02 +0200 Subject: [PATCH] feat(input): autosize sets default amount of rows to one (#4906) * The autosize directive now sets the rows property of the textarea to one by default. * This is necessary because browsers by default set the rows property to two and therefore setting the minRows and maxRows binding to something below two doesn't work. Fixes #4852 --- src/lib/input/autosize.spec.ts | 21 +++++++++++++++++++++ src/lib/input/autosize.ts | 6 +++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/lib/input/autosize.spec.ts b/src/lib/input/autosize.spec.ts index 698c1ea5a575..ce28391264c7 100644 --- a/src/lib/input/autosize.spec.ts +++ b/src/lib/input/autosize.spec.ts @@ -103,6 +103,27 @@ describe('MdTextareaAutosize', () => { expect(fixture.componentInstance.autosize.resizeToFitContent).toBeTruthy(); }); + it('should initially set the rows of a textarea to one', () => { + expect(textarea.rows) + .toBe(1, 'Expected the directive to initially set the rows property to one.'); + + fixture.componentInstance.minRows = 1; + fixture.detectChanges(); + + expect(textarea.rows) + .toBe(1, 'Expected the textarea to have the rows property set to one.'); + + const previousMinHeight = parseInt(textarea.style.minHeight); + + fixture.componentInstance.minRows = 2; + fixture.detectChanges(); + + expect(textarea.rows).toBe(1, 'Expected the rows property to be set to one. ' + + 'The amount of rows will be specified using CSS.'); + + expect(parseInt(textarea.style.minHeight)) + .toBeGreaterThan(previousMinHeight, 'Expected the textarea to grow to two rows.'); + }); it('should properly resize to content on init', () => { // Manually create the test component in this test, because in this test the first change diff --git a/src/lib/input/autosize.ts b/src/lib/input/autosize.ts index a274ac68673c..4d737a5fea23 100644 --- a/src/lib/input/autosize.ts +++ b/src/lib/input/autosize.ts @@ -10,6 +10,9 @@ import {Directive, ElementRef, Input, AfterViewInit} from '@angular/core'; exportAs: 'mdTextareaAutosize', host: { '(input)': 'resizeToFitContent()', + // Textarea elements that have the directive applied should have a single row by default. + // Browsers normally show two rows by default and therefore this limits the minRows binding. + 'rows': '1', }, }) export class MdTextareaAutosize implements AfterViewInit { @@ -116,7 +119,8 @@ export class MdTextareaAutosize implements AfterViewInit { /** Resize the textarea to fit its content. */ resizeToFitContent() { - let textarea = this._elementRef.nativeElement as HTMLTextAreaElement; + const textarea = this._elementRef.nativeElement as HTMLTextAreaElement; + // Reset the textarea height to auto in order to shrink back to its default size. textarea.style.height = 'auto';