FormControl:setValue don't fire input event
Asked Answered
F

2

5

I have a form with a notes field bounded by a textarea.

this.form = this.formBuilder.group({});
this.form.addControl('notes', new FormControl(''));

The template have an autoresize directive attached.

<textarea formControlName="notes" autosize></textarea>

Such a directive resizes the height of the textarea every time the user change its content.

@HostListener('input')
public onChange(textArea: HTMLTextAreaElement): void {
    const textarea = this.element.nativeElement.querySelector('textarea');
    this.renderer.setStyle(textarea, 'overflow', 'hidden');
    this.renderer.setStyle(textarea, 'height', 'auto');
    this.renderer.setStyle(textarea, 'height', `${textarea.scrollHeight}px`);
  }

However, when I programmatically change the value of the FormControl, the input event is not fired, and the textarea is not resized accordingly.

this.form.controls['notes'].setValue('a new value'); // not firing events

What am I doing wrong?

Farrell answered 25/6, 2018 at 14:56 Comment(0)
P
6

Instead of input you can bind to ngModelChange that will be triggered on both events:

@HostListener('ngModelChange') onNgModelChange() {
  console.log('ngModelChange');
}

See demo: https://stackblitz.com/edit/angular-basic-template-say51l?file=src%2Fapp%2Fautosize.directive.ts

Pashalik answered 25/6, 2018 at 16:24 Comment(0)
G
0

After a quick glance you misspelled autoresize, in your case it is autosize:

<textarea formControlName="notes" autosize></textarea>
Glarus answered 25/6, 2018 at 14:59 Comment(1)
While it may be grammatically incorrect, that's the name of the directive. It's worth nothing that the resizing works well when the user input something. The problem occurs only when I change the value programmatically.Farrell

© 2022 - 2024 — McMap. All rights reserved.