Lightbringer
Lightbringer

Reputation: 819

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?

Upvotes: 2

Views: 1772

Answers (2)

Xinan
Xinan

Reputation: 3162

trigger a change event on a textarea when setting the value via ngModel Binding

This will cause infinite triggering if you do so.

If you don't want to monitor the input model change in a more reactive way, a quicker solution (but a bit hacky) will be simply wrap your code inside setTimeout in ngOnInit() or ngAfterViewInit() where you mentioned it was not working.

setTimeout(() => {
  updateSize();
});

Upvotes: 1

Nikhil Arora
Nikhil Arora

Reputation: 141

Yes there is a very simple solution for this. Wrap your textarea inside a form and try the code below:-

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();
}

Upvotes: 2

Related Questions