ion-textarea resize height dynamically in Ionic 5
Asked Answered
C

1

4

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.

Choler answered 12/4, 2020 at 17:13 Comment(3)
Add autoGrow="true" attribute in ion-textarea and it will auto inrease,Alrick
Thanks. This works perfectly. Please put your comments in the Answer so that I can make it the correct answer.Choler
Your welcime mate <3. I did add it as answer.Alrick
A
9

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

<ion-textarea #hvUserPost type="text"autoGrow="true" (input)="adjustDesc()"></ion-textarea>
Alrick answered 13/4, 2020 at 10:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.