何时何地调用 updateValueAndValidity?

When and where to call updateValueAndValidity?

我不清楚应该在何时何地调用 updateValueAndValidity.

假设我有一个包含许多 formControl 的 formGroup。 现在,基于某些单选选项选择,将触发一个事件来修改多个 formControl 的 'validators'。

Q1:我是在修改后立即调用updateValueAndValidity还是在所有修改调用完成后调用?

Q2:我是不是要通过表单更新formGroup/formControls来更新所有的formControls

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

或单独调用每个 formControls

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

为了安全起见,您需要调用所有控件的更新

在这个答案中你可以看到这个函数(updateValueAndValidity)更新父

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.

注意行 它不会沿着树向下,只会向上 所以如果你调用 form 上的函数,controls 可能没有所需的行为,但更新控件将反映在表单上

尽管可能很麻烦,但您需要更新每个控件的值和有效性