Skip to content
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

feat(textarea): add autosize directive #1632

Closed
wants to merge 1 commit into from
Closed
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
25 changes: 25 additions & 0 deletions src/demo-app/input/input-demo.html
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,31 @@ <h4>Textarea</h4>
</md-card-content>
</md-card>

<md-card class="demo-card demo-basic">
<md-toolbar color="primary">Expanding textarea</md-toolbar>
<md-card-content>
<div>
<md-textarea
placeholder="Textarea with autosize"
class="demo-full-width"
autosize
value="Hello world. How are you?">
</md-textarea>
</div>

<h4>With `rows` explicitly set</h4>
<div>
<md-textarea
placeholder="Textarea with autosize"
class="demo-full-width"
autosize
[rows]="rows"
value="Hello world. How are you?">
</md-textarea>
</div>
</md-card-content>
</md-card>

<md-card class="demo-card">
<md-card-title>
Hello <md-input [(ngModel)]="name" type="text" placeholder="First name"></md-input>,
Expand Down
1 change: 1 addition & 0 deletions src/lib/input/input.html
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
[attr.rows]="rows"
[attr.wrap]="wrap"
[autofocus]="autofocus"
[mdAutosize]="autosize"
[disabled]="disabled"
[id]="inputId"
[attr.maxlength]="maxlength"
Expand Down
131 changes: 129 additions & 2 deletions src/lib/input/input.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import {
Input,
Directive,
AfterContentInit,
OnInit,
HostListener,
ContentChild,
SimpleChange,
ContentChildren,
Expand Down Expand Up @@ -87,6 +89,126 @@ export class MdHint {
@Input() align: 'start' | 'end' = 'start';
}


/**
* Enables auto expanding behaviour for the textarea
* based on: https://github.com/stevepapa/angular2-autosize
*/
@Directive({
selector: 'textarea[mdAutosize]'
})
export class MdAutosize implements OnInit {
// public because of AOT
@HostListener('input')
_onChange() {
if (this._isActive) {
this._adjust();
}
}

// public because of AOT
@Input('mdAutosize')
_isActive: boolean;

// public because of AOT
// TODO: change to a setter, to recalculate on change
@Input('attr.rows')
_rows: string;

private _height: number;
private _lineHeight: number;

constructor(private _elRef: ElementRef) {}

ngOnInit() {
console.log(this._isActive);

if (this._isActive) {
this._elRef.nativeElement.style.overflow = 'hidden';

// check is rows is explicitly set, otherwise we don't need to
// care about it(and getting the actual line-height) at all
if (this._rows) {
this._lineHeight = this._getLineHeight();
this._elRef.nativeElement.style.minHeight = `${+this._rows * this._lineHeight}px`;
}

this._adjust();
}
}

private _adjust() {
// reset height(and rows if it was set by the user)
// to the default values to properly calculate new height
this._elRef.nativeElement.style.height = 'auto';

// only need to do this if user explicitly set rows
if (this._rows) {
this._elRef.nativeElement.rows = this._rows;
}

this._height = +this._elRef.nativeElement.scrollHeight;

// only need to do this if user explicitly set rows
if (this._rows) {
this._elRef.nativeElement.rows = this._getCalculatedRows();
}

this._elRef.nativeElement.style.height = `${this._height}px`;
}

private _getCalculatedRows() {
return Math.round(this._height / this._lineHeight);
}

private _getLineHeight(): number {
const el: HTMLTextAreaElement = this._elRef.nativeElement;

// get the actual computed styles for the element
const computedStyles = window.getComputedStyle(el);

// if line height is explicitly set(to a pixel value), use that
if (computedStyles.lineHeight && computedStyles.lineHeight.toLowerCase().indexOf('px') >= 0) {
// return stripped of the "px" and as a number
return parseFloat(computedStyles.lineHeight);
}

// create temporary element
const tempEl = <HTMLTextAreaElement>document.createElement(el.nodeName);

// reset styling, visually hiden the element
// and set its font styles to match the ones of our textarea
tempEl.setAttribute('rows', '1');
tempEl.setAttribute(
'style',
`
margin: 0px;
padding: 0px;
visibility: hidden;
opacity: 0;
font-family: ${computedStyles.fontFamily};
font-size: ${computedStyles.fontSize};
`
);

// fill in one row
tempEl.value = '-';

// append to parent element to correctly inherit same values
// as the actual textarea
el.parentNode.appendChild(tempEl);

// get the actual line height
const lineHeight = tempEl.clientHeight;

// cleanup
tempEl.parentNode.removeChild(tempEl);

return lineHeight;
}
}


/**
* Component that represents a text input. It encapsulates the <input> HTMLElement and
* improve on its behaviour, along with styling it according to the Material Design.
Expand Down Expand Up @@ -174,6 +296,7 @@ export class MdInput implements ControlValueAccessor, AfterContentInit, OnChange

private _floatingPlaceholder: boolean = true;
private _autofocus: boolean = false;
private _autosize: boolean = false;
private _disabled: boolean = false;
private _readonly: boolean = false;
private _required: boolean = false;
Expand Down Expand Up @@ -203,6 +326,10 @@ export class MdInput implements ControlValueAccessor, AfterContentInit, OnChange
get spellcheck(): boolean { return this._spellcheck; }
set spellcheck(value) { this._spellcheck = coerceBooleanProperty(value); }

// textarea-specific
@Input()
get autosize(): boolean { return this._autosize; }
set autosize(value) { this._autosize = coerceBooleanProperty(value); }

private _blurEmitter: EventEmitter<FocusEvent> = new EventEmitter<FocusEvent>();
private _focusEmitter: EventEmitter<FocusEvent> = new EventEmitter<FocusEvent>();
Expand Down Expand Up @@ -360,9 +487,9 @@ export class MdInput implements ControlValueAccessor, AfterContentInit, OnChange


@NgModule({
declarations: [MdPlaceholder, MdInput, MdHint],
declarations: [MdPlaceholder, MdInput, MdHint, MdAutosize],
imports: [CommonModule, FormsModule],
exports: [MdPlaceholder, MdInput, MdHint],
exports: [MdPlaceholder, MdInput, MdHint, MdAutosize],
})
export class MdInputModule {
static forRoot(): ModuleWithProviders {
Expand Down