Skip to content

Instantly share code, notes, and snippets.

@kinoli
Created September 13, 2017 22:14
Show Gist options
  • Save kinoli/da7aee28934ec5728fb28d1ac3548230 to your computer and use it in GitHub Desktop.
Save kinoli/da7aee28934ec5728fb28d1ac3548230 to your computer and use it in GitHub Desktop.
Auto resize directive for TextAreas in Angular 2/4
// An autoresize directive that works with ion-textarea in Ionic 2
// Usage example: <ion-textarea autoresize [(ngModel)]="body"></ion-textarea>
// Usage example: <ion-textarea autoresize="100" [(ngModel)]="body"></ion-textarea>
// Based on https://www.npmjs.com/package/angular2-autosize
import { Directive, HostListener, ElementRef, Input } from "@angular/core";
@Directive({
selector: "ion-textarea[autoresize]" // Attribute selector
})
export class AutoresizeDirective {
@HostListener('input', ['$event.target'])
onInput(textArea: HTMLTextAreaElement): void {
this.adjust();
}
@Input('autoresize') maxHeight: number;
constructor(public element: ElementRef) {
}
ngOnInit(): void {
this.adjust();
}
adjust(): void {
let ta = this.element.nativeElement.querySelector("textarea"),
newHeight;
if (ta) {
ta.style.overflow = "hidden";
ta.style.height = "auto";
if (this.maxHeight) {
console.log('this.maxHeight',this.maxHeight)
newHeight = Math.min(ta.scrollHeight, this.maxHeight);
console.log('newHeight',newHeight)
} else {
newHeight = ta.scrollHeight;
}
ta.style.height = newHeight + "px";
}
}
}
@FallenRiteMonk
Copy link

Thanks, this works great.
Do you think this could be somehow merged into ionic?
Try creating a pull request!

As an idea for an improvement, do you think this could be changes so that max height is not in px but in rows?

@stewones
Copy link

Thanks, pretty awesome.

@javaHelper
Copy link

Does this works well in detail page as well ?

@fortunatogreco
Copy link

Good!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment