javascripthtmlcssangulartextarea

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);
   });
});

Solution

  • 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.