Home:ALL Converter>Angular - Textarea auto height does not automatically resize on text deletion

Angular - Textarea auto height does not automatically resize on text deletion

Ask Time:2018-07-19T23:46:41         Author:user9410919

Json Formatter

I am using the following directive to allow an auto-sizing to a text area depending on user input:

import { ElementRef, HostListener, Directive, OnInit } from '@angular/core';

@Directive({
  selector: 'ion-textarea[autosize]'
})

export class Autosize implements OnInit {
  @HostListener('input', ['$event.target'])
  onInput(textArea:HTMLTextAreaElement):void {
    this.adjust();
  }

  constructor(public element:ElementRef) {
  }

  ngOnInit():void {
    setTimeout(() => this.adjust(), 0);
  }

  adjust():void {
    const textArea = this.element.nativeElement.getElementsByTagName('textarea')[0];
      textArea.style.height = 'auto';
      textArea.style.height = textArea.scrollHeight + "px";
      textArea.style.maxHeight = '100px';
  }
}

It is working as intended, however when the text inside that textarea is manually deleted, the textarea will not resize automatically.

E.g. if the [(ngModel)] variable assigned to that textarea is assigned a different string, or empty string, the height of the text area will not automatically resize. The user needs to start typing again in order to make the textarea resize accordingly.

What could be a good solution to solving this issue?

Author:user9410919,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/51426940/angular-textarea-auto-height-does-not-automatically-resize-on-text-deletion
yy