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.
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);
});
});
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.
For anyone still looking for an answer to this in almost 2021, it's covered in the official Angular Material docs here. Directly manipulating the DOM via nativeElement
is an anti-pattern.
<mat-form-field [style.fontSize]="fontSize.value">
<mat-label>Autosize textarea</mat-label>
<textarea matInput
cdkTextareaAutosize
#autosize="cdkTextareaAutosize"
cdkAutosizeMinRows="1"
cdkAutosizeMaxRows="5"></textarea>
</mat-form-field>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With