Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to auto resize the textarea to fit the content?

I'm trying to auto resize the textarea so it fits the content in it but I'm facing a stuttering issue after I click enter to proceed to the next line. How can I fix this?

This is what I'm trying to do, see the image below. enter image description here

Please see this link for the StackBlitz example

CODE

this.form.valueChanges.subscribe(() => {
   const textarea = this.myDiv.nativeElement;
   textarea.addEventListener('keydown', function() {
       setTimeout(() => {
           this.style.cssText = 'height:auto; padding:0';
           this.style.cssText = 'height:' + this.scrollHeight + 'px';
       }, 0);
   });
});
like image 884
Joseph Avatar asked Sep 24 '19 04:09

Joseph


2 Answers

addEventListener here is redundant since valueChanges already notifies you when the field changes. Instead, update the height using the ViewChild reference myDiv.

this.myForm.valueChanges.subscribe(value => {
    this.myDiv.nativeElement.style.height = 'auto';
    this.myDiv.nativeElement.style.height = `${this.myDiv.nativeElement.scrollHeight}px`;
});

Then add overflow: hidden to your css so the scrollbar doesn't show.

textarea {
    resize: horizontal;
    overflow: hidden;
}

You can keep the resize: horizontal; but it is no longer required since the textarea will resize automatically anyway.

Here is a working example on StackBlitz.

like image 63
nash11 Avatar answered Sep 28 '22 00:09

nash11


For anyone still looking for an answer to this in almost 2021, it's covered in the official Angular Material docs here. Directly manipulating the DOM via nativeElement is an anti-pattern.

<mat-form-field [style.fontSize]="fontSize.value">
  <mat-label>Autosize textarea</mat-label>
  <textarea matInput
            cdkTextareaAutosize
            #autosize="cdkTextareaAutosize"
            cdkAutosizeMinRows="1"
            cdkAutosizeMaxRows="5"></textarea>
</mat-form-field>
like image 38
Meqwz Avatar answered Sep 28 '22 00:09

Meqwz