Hi,
I’m trying to auto-adjust the height of a text area using this directive: Here
It’s works when i manually type in the text area but if i add a button to set a multiline text into the text area, the height won’t adjust automaticaly.
How can I handle it ?
Thank you
MattE
March 7, 2018, 10:44am
2
Is this what you’re looking for?
I’ve changed some code, according to the code I use in my apps.
1 Like
Thank you for your response but i don’t see any difference in the code between your link and my link
MattE
March 7, 2018, 12:07pm
4
https://stackblitz.com/edit/expandable-input-yrfnrf
I’ve added a button using your directive but it still doesn’t work
ramon
March 7, 2018, 2:56pm
7
This is my AutoResizeTextareaDirective:
import {Directive, HostListener, ElementRef, Input, OnInit} from '@angular/core';
@Directive({
selector: '[auto-resize-textarea]'
})
export class AutoResizeTextareaDirective implements OnInit {
@HostListener('input', ['$event.target'])
onInput(textArea: HTMLTextAreaElement): void {
this.adjust();
}
@Input('auto-resize-textarea') maxHeight: number;
constructor(public element: ElementRef) {}
ngOnInit(): void {
setTimeout(() => {
this.adjust();
}, 500);
}
adjust(): void {
let ta = this.element.nativeElement.querySelector("textarea");
if (ta) {
ta.style.overflow = "hidden";
ta.style.height = null;
ta.style.height = Math.min(ta.scrollHeight, this.maxHeight) + "px";
} else {
this.element.nativeElement.style.overflow = "hidden";
this.element.nativeElement.height = null;
this.element.nativeElement.style.height = Math.min(this.element.nativeElement.scrollHeight, this.maxHeight) + "px";
}
}
}
To use that simply add the attribute auto-resize-textarea to your ion-textarea with a max-height in pixels:
<ion-textarea [formControlName]="biography" [auto-resize-textarea]="320" ></ion-textarea>
2 Likes
Thank you ramon but i have the same problem.
https://stackblitz.com/edit/expandable-input-it2onm
Maybe i do something wrong ?
ramon
March 7, 2018, 4:06pm
9
Sorry, @bbarascou , I did not see that the directive you used was the same as the one I used.
I am trying to find a solution.
I’ll tell you if there is any progress with this.
After a lot of frustration I did something like this
var breaklines = (ev.target.value.split(/\r?\n|\r/)).length;
var textlines = ev.target.value.length / 30;
ev.target.rows = Math.round(textlines) + breaklines;
Inside the ionChange event handler where ev = element’s event
this package does all the autosizing of my ion-textareas for me https://github.com/chrum/ngx-autosize just follow the guide and get it working, if it doesn’t work importing it into the app.module.ts then try importing it into the page’s module, I personally needed that dunno if you will, but package is a life saver
3 Likes
jjdev
May 22, 2019, 5:11pm
13
As of v4.4.0, ion-textarea has a autoGrow
directive
GitHub - Ionic 4.4.0 textarea changes
I haven’t tested it but it is there
1 Like