首页 > 解决方案 > How to trigger a change event on a textarea when setting the value via ngModel Binding

问题描述

I have a <textarea> within a template driven form of an Angular 7 project. When editing an object, the form is prefilled with the current values. I want to automatically resize the <textarea> when the content has changed via the [(ngModel)]="property" binding by modifying the element-style.

area.style.overflow = 'hidden';
area.style.height = '0';
area.style.height = area.scrollHeight + 'px';

The code generally is working, but I cannot find a suitable event to trigger it. Subscribing to the change event of the <textarea> is only working on keyboard input. Using (ngModelChange)="adjustTextAreaSize($event)" has the same behavior.

I tried to execute my resizing code at the end of the ngOnInit() function, but the actual html-control seems to not have any content yet at this point.

Does anyone have an idea which event could do the trick here? Seemed a rather easy task in the beginning, but I'm breaking my had over this for over an hour now... can not be such a difficult task, can it?

标签: htmlangularbindingtextarea

解决方案


是的,有一个非常简单的解决方案。将您的textarea内部包裹起来form并尝试以下代码:-

HTML

<form #form="ngForm">
   <textarea>....</textarea>
</form>

TS

@ViewChild('form') ngForm: NgForm;
ngOnInit() {
  this.subscription = this.ngForm.form.valueChanges.subscribe(resp => 
    {
      console.log(resp); // You get your event here
    }
)
}

ngOnDestroy() {
  this.subscription.unsubscribe();
}

推荐阅读