角度6,this.formGroup.updateValueAndValidity()无法正常工作 [英] Angular 6, this.formGroup.updateValueAndValidity() not working properly

查看:98
本文介绍了角度6,this.formGroup.updateValueAndValidity()无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to add and remove validators in a formGroup controls based on certain condition.

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

When I am updating the validators through formGroup.updateValueAndValidity() for whole form its not updating, where as if I am specifically applying for each Control i.e. formGroup.get('formControl').updateValueAndValidity(), it is working but i have to write for each control which is i hope not the correct way. What am i doing wrong?

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();

这不起作用.

推荐答案

updateValueAndValidity()是自底向上的,因此,如果您通过控件调用此方法,它将仅检查该控件的验证和他们的父母,而不是他们的孩子.

updateValueAndValidity() is bottom-up, so if you call this method over a control, it will check only validations of this control and their parents, but not their children.

有关更多详细信息,请参见 AbstractControl#updateValueAndValidity 了解其工作原理.

For more details, see AbstractControl#updateValueAndValidity on github to how it works.

  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);
    }
  }

这篇关于角度6,this.formGroup.updateValueAndValidity()无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆