1

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Try starting by initializing labelValue to '' first (when you declare it), and then assign its value as you should be doing now.

1 Comment

Thanks for your response, well the labelValue is a property of an object that is filled from the response of an API request like this.question = <api response> where question object contains the labelValue property so I think it does not matter whether the labelValue property is initialized to '' at first

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.