Skip to content
Advertisement

Angular – Adjust two way binded input element’s height according to the length of its content

I want to make the height of my input text adjusted to its text content. I can easily achieve that when the user is filling the content by triggering the (input) event, which calls my adjustHeight function which updates the height of the input element using the scrollHeight.

Code example below:

 <textarea #myLabel
       (input)="adjustHeight(myLabel)"
       [(ngModel)]="labelValue">
 </textarea>


 adjustHeight(element: HTMLElement) {
   element.style.height = "5px";
   element.style.height = (element.scrollHeight)+"px";
 }

This works fine when the user is filling the input element, but when the input text is rendered with an already filled labelValue, (coming from an API response) the height of the textarea is not changed dynamically since no (input) event gets triggered.

I tried to use (ngModelChange) event but it does not seem to be triggered. Is there any other event that could be binded to the input element to take care of its height on rendering? Thanks in advance

Answer

template:

<textarea #myLabel
    [style.height]="getHeight(myLabel)" 
    [(ngModel)]="labelValue">
</textarea>

typescript:

public getHeight(element: HTMLElement): string {
    return element.scrollHeight + 'px';
}

this way, the style will change whenever necessary.

Advertisement