41

These docs state the following:

If emitEvent is true, this change will cause a valueChanges event on the FormControl to be emitted. This defaults to true (as it falls through to updateValueAndValidity).

What is this updateValueAndValidity?

Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488

3 Answers3

37

You can subscribe to value changes of a control or the whole form.

updateValueAndValidity allows you to modify the value of one or more form controls and the flag allows you to specify if you want this to emit the value to valueChanges subscribers.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 1
    thanks, I don't see where `updateValueAndValidity` should be configured – Max Koretskyi Feb 13 '17 at 06:30
  • 1
    https://angular.io/docs/ts/latest/api/forms/index/AbstractControl-class.html#!#updateValueAndValidity-anchor – Günter Zöchbauer Feb 13 '17 at 06:32
  • 1
    I have a required field, after I clear the validity using clearValidators() the required validator is not in effect and my form has no errors, I also set the required validity with setValidators([Validators.required]) and it updates right away. Do I still need to invoke updateValueAndValidity()? The form control is clearing and updating validity even without it. – farfly Dec 10 '19 at 17:36
  • You only need to call it if you want behavior different from the default behavior. – Günter Zöchbauer Dec 10 '19 at 18:00
23

The sourcecode can be helpful to clear up exactly what it's doing:

https://github.com/angular/angular/blob/master/packages/forms/src/model.ts

Currently it seems to be doing the following (this list is based on method names):

  • 'Set initial status' - which makes .status 'VALID' except if ALL controls are disabled, in which case it makes it 'DISABLED'
  • 'Updates value' - this seems to set .value if the control is enabled, or clear it if disabled.
  • 'Runs validator' - this updates the whole error object. So custom errors would be cleared if you'd set any.
  • 'Cancel subscriptions' - stops any async validators running at the time
  • 'Emit' event - (if emitEvent != false in options). This is just the value and status normal form events.
  • Updates parent with same rules - unless onlySelf is set.

Note: it doesn't go down the tree, only up.

I wish they'd put something like this in the docs. They currently say 'Recalculates the value and validation status of the control.' which isn't particularly helpful.

Simon_Weaver
  • 140,023
  • 84
  • 646
  • 689
2

The updateValueAndValidity() method belongs to the AbstractFormControl class, used to validate your forms programmatically.

Basically, when you add or remove a validator at run time, you must call updateValueAndValidity() for the new validation to take effect.