Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bipoza/2b0c9f05725abe15b92b28ae26203481 to your computer and use it in GitHub Desktop.
Save bipoza/2b0c9f05725abe15b92b28ae26203481 to your computer and use it in GitHub Desktop.
textarea autosize directive for ionic/angular 4 (updated to work with 4.0.0)
import { Directive, ElementRef, OnInit } from '@angular/core';
import { Observable, fromEvent } from 'rxjs';
import { DomController } from '@ionic/angular';
@Directive({
selector: 'ion-textarea[autosize]'
})
export class TextareaAutosizeDirective implements OnInit {
private inputObservable: Observable<any>;
constructor(private el: ElementRef, private domCtrl: DomController) { }
ngOnInit() {
const mutationObserver = new MutationObserver(() => {
this.el.nativeElement.style.height = `${this.el.nativeElement.lastChild.scrollHeight}px`;
this.inputObservable = fromEvent(this.el.nativeElement.querySelector('textarea'), 'input');
this.inputObservable.subscribe((inputEvent: any) => {
const textAreaNative = inputEvent.target;
this.domCtrl.write(() => {
this.el.nativeElement.style.height = 'auto';
textAreaNative.style.height = 'auto';
textAreaNative.style.height = `${textAreaNative.scrollHeight}px`;
});
});
});
mutationObserver.observe(this.el.nativeElement, {
childList: true,
});
}
}
@bipoza
Copy link
Author

bipoza commented Jan 2, 2020

Usage: <ion-textarea autosize [(ngModel)]="textdata"></ion-textarea>

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