Search code examples
angulareventsangular2-formbuilder

FormControl:setValue don't fire input event


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?


Solution

  • 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