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

Discussão em 'Angular' iniciado por user9410919, Dezembro 5, 2024.

  1. user9410919

    user9410919 Guest

    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?

    Continue reading...

Compartilhe esta Página