Last active
June 19, 2021 07:43
-
-
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)
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
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, | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
or
<ion-textarea auto-grow="true">my text</ion-textarea>
in ionic 4.4 ;)