Skip to content

Instantly share code, notes, and snippets.

@kplhub
Last active June 19, 2021 07:43
Show Gist options
  • Save kplhub/bcafca43dca3adda26214f0b50277b17 to your computer and use it in GitHub Desktop.
Save kplhub/bcafca43dca3adda26214f0b50277b17 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,
});
}
}
@kplhub
Copy link
Author

kplhub commented Jan 21, 2019

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

@Snargol
Copy link

Snargol commented Feb 17, 2020

or <ion-textarea auto-grow="true">my text</ion-textarea> in ionic 4.4 ;)

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