首页 > 解决方案 > Angular 6,this.formGroup.updateValueAndValidity() 无法正常工作

问题描述

我正在尝试formGroup根据特定条件在控件中添加和删除验证器。

当我通过formGroup.updateValueAndValidity()整个表单更新验证器时,它没有更新,就好像我专门为每个控件申请一样formGroup.get('formControl').updateValueAndValidity(),它正在工作,但我必须为每个控件编写,我希望这不是正确的方法。我究竟做错了什么?

if (data == 'x') {
    this.myForm.get('control2').setValue(null);
    this.myForm.get('control2').setValidators(Validators.nullValidator);
    this.myForm.get('control1').setValidators(Validators.required);
} else if (data == 'y') {
    this.myForm.get('control1').setValue(null);
    this.myForm.get('control1').setValidators(Validators.nullValidator);
    this.myForm.get('control2').setValidators(Validators.required);
}
this.myForm.get('control1').updateValueAndValidity();
this.myForm.get('control2').updateValueAndValidity();

这是有效的,但是,

this.myForm.updateValueAndValidity();

这是行不通的。

标签: angulartypescriptform-controlformgroupsangular-validator

解决方案


updateValueAndValidity()是自下而上的,因此如果您在控件上调用此方法,它将仅检查此控件及其父控件的验证,但不检查其子控件。

有关更多详细信息,请参阅github 上的AbstractControl#updateValueAndValidity以了解其工作原理。

  updateValueAndValidity(opts: {onlySelf?: boolean, emitEvent?: boolean} = {}): void {
    this._setInitialStatus();
    this._updateValue();

    if (this.enabled) {
      this._cancelExistingSubscription();
      (this as{errors: ValidationErrors | null}).errors = this._runValidator();
      (this as{status: string}).status = this._calculateStatus();

      if (this.status === VALID || this.status === PENDING) {
        this._runAsyncValidator(opts.emitEvent);
      }
    }

    if (opts.emitEvent !== false) {
      (this.valueChanges as EventEmitter<any>).emit(this.value);
      (this.statusChanges as EventEmitter<string>).emit(this.status);
    }

    if (this._parent && !opts.onlySelf) {
      this._parent.updateValueAndValidity(opts);
    }
  }

推荐阅读