htmlionic-frameworkionic5elementref

ion-textarea resize height dynamically in Ionic 5


I am migrating my project from Ionc3 to Ionic5. I have an ion-textarea which increases the height as user types and it works in Ionic3. Following is the code.

HTML page:

<ion-textarea #hvUserPost type="text" (input)="adjustDesc()"></ion-textarea>

TS page:

@ViewChild('hvUserPost') hvUserPost: ElementRef;
adjustDesc() {
    let textArea;
    textArea = this.hvUserPost['_elementRef'].nativeElement.getElementsByClassName("text-input")[0];
    textArea.style.overflow = 'hidden';
    textArea.style.height = 'auto';
    var scrollHeight = textArea.scrollHeight;
    textArea.style.height = scrollHeight + 'px';
}

Now in Ionic4 the only thing changes is in the following declaration

@ViewChild('hvUserPost', {static: false}) hvUserPost: ElementRef;

In Ionic4, I am getting the following error.

ERROR TypeError: Cannot read property 'nativeElement' of undefined

So this.hvUserPost['_elementRef'] is undefined and this.hvUserPost.nativeElement is also undefined.


Solution

  • Just add autoGrow="true" atteibute and it will be done.

    <ion-textarea #hvUserPost type="text"autoGrow="true" (input)="adjustDesc()"></ion-textarea>