angularvalidationangular2-form-validation

When and where to call updateValueAndValidity?


I'm unclear on when and where exactly I should be calling the updateValueAndValidity.

Let's say I have a formGroup with many formControls. Now, based on some radio option selection an event fires to modify the 'validators' for several formControls.

Q1: Am I to call updateValueAndValidity immediately after modifications or after all modification calls have been done?

Q2: Am I to update the formGroup / formControls via the form to update all formControls

this.form.updateValueAndValidity('emitEvent': false);

or call each formControls individually

this.form.get('control1').updateValueAndValidity('emitEvent': false);
this.form.get('control3').updateValueAndValidity('emitEvent': false);
this.form.get('control8').updateValueAndValidity('emitEvent': false);

Solution

  • You need to call the update on all controls to be safe

    In this answer https://stackoverflow.com/a/54045398/13680115 You can see the line that this function (updateValueAndValidity) updates the parent

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

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

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

    Note the line It doesn't go down the tree, only up so if you call the function on the form, the controls may not have the desired behavior but updating the controls will be reflected on the form

    So as cumbersome as it maybe, you will need to update each controls' value and validity