[SOLVED] Ion-textarea resize height dynamically

This is old code, so can’t vouch for functionality against recent ionic builds. Basically, a resize function is triggered on every keyup event generated as the user types:

<textarea (keyup)="resize( $event)" [class]="'placeholder-'+type" #myInput formControlName="body" type="text" rows="1" maxLength="150" >

In the page component the resize function resizes the input field based on the new scrollHeight:

  resize(event?) {
    console.log('keycode:', event)
    if (event && event.keyCode === 13) {
      this.submitMessage()
    } else {
      this.myInput.nativeElement.style.height = 'auto'
      this.myInput.nativeElement.style.height = this.myInput.nativeElement.scrollHeight + 'px'
      console.log('resized textarea')
    }
  }

hth

I really like what you did and i am trying to scroll the text…
My queastion is can we fix from .ts file or have to do in css file?

Thank bro its work for me

thing is, using the directive works fine on browser but it doesn’t seem to work for me on android

resize() {
this.myInput.nativeElement.style.height = ‘auto’
this.myInput.nativeElement.style.height = this.myInput.nativeElement.scrollHeight + ‘px’;
}
This works for auto height reduction ! Thank you.

1 Like

With ionic-5 , there is an option called auto-grow, set it to true in your view.
In css, set min-height, max-height, to control the text grow.

ion-textarea {
min-height: 100px;
max-height: 200px;
}

Also, after the above fix, if you get some odd behaviour with placeholder text, add below inside the ion-textarea

::ng-deep textarea {
min-height: 100px;
}

In Ionic 5 use autoGrow = true like:
<ion-textarea auto-grow placeholder="description"></ion-textarea>

1 Like