Created
September 13, 2017 22:14
-
-
Save kinoli/da7aee28934ec5728fb28d1ac3548230 to your computer and use it in GitHub Desktop.
Auto resize directive for TextAreas in Angular 2/4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"; | |
} | |
} | |
} |
Thanks, pretty awesome.
Does this works well in detail page as well ?
Good!!!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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?