How to fire the `valueChanges` programmatically?

Max picture Max · Feb 24, 2017 · Viewed 37.8k times · Source

On one of my pages I use a FormBuilder to fill a form at initialization. Every input gets a class whenever the input is not empty. This is done by adding a ngClass to every input, and subscribing on the FormGroup's valueChanges.

My problem occurs whenever the form is filled programmatically. Whenever a user changes any value on the form, valueChanges gets called, however, this is not the case when using a FormBuilder.

My question is: How to get the valueChanges event to be fired whenever the FormBuilder is finished.

I have tried using this.FormGroup.updateValueAndValidity(), but this did not result in anything.

Answer

Max picture Max · Feb 24, 2017

I found a solution which worked for me. I forgot two parameters in the updateValueAndValidity function.

  • onlySelf: will only update this FormControl when true.
  • emitEvent: will cause valueChanges event to be fired when true.

So as result you will get something like: FormGroup.updateValueAndValidity({ onlySelf: false, emitEvent: true });