首页 > 解决方案 > 角度异步验证器“updateOn”和特定条件

问题描述

我试图让一个异步验证器只触发 onblur 并且如果布尔值为真。

我想我可以通过将 updateOn args 转换为数组并添加第二个对象来使其工作,如下所示:

this.createOrganisation.addControl('address', this.ofb.group(
        {                
            addressPostcode: [null, { validators: [Validators.required], asyncValidators: [this.postCodeValidator], updateOn: [ 'blur', this.showAlert] }]

        }   
    ));

顺便提一句:

this.showAlert

设置为假。

任何人都知道如何仅验证模糊以及该布尔值是否设置为true?

标签: angulartypescriptasynchronous

解决方案


updateOn只接受'change' | 'blur' | 'submit'字符串并且应该只处理那些事件,你不能通过使其成为一个数组来使其工作。

据我了解,在您的案例中添加验证器的决定因素是showAlert标志。如果 onlyshowAlert为真,那么我们需要检查是否对blur事件进行验证。如果这个假设是正确的并且您没有在事件showAlert期间更新标志,blur那么您可以使用这种方法。

我根据showAlert标志状态设置带有和不带有验证器的表单控件。让它的 setter/getter 像:

set showAlert(val) {
    this._showAlert = val
    this._modifyControl()
}

get showAlert() {
  return this._showAlert
}

private _modifyControl() {
  if (this.showAlert) {
    if (this.createOrganisation.get('addressPostcode')) {
      let controlValue = this.createOrganisation.get('addressPostcode').value
      this.createOrganisation.setControl('addressPostcode', new FormControl(controlValue, { validators: [Validators.required], asyncValidators: [this.postCodeValidator.bind(this)], updateOn: 'blur' }))
    }
    else {
      this.createOrganisation.addControl('addressPostcode', new FormControl(null, { validators: [Validators.required], asyncValidators: [this.postCodeValidator.bind(this)], updateOn: 'blur' }))
    }
    
  }
  else {
    if (this.createOrganisation.get('addressPostcode')) {
      let controlValue = this.createOrganisation.get('addressPostcode').value
      this.createOrganisation.setControl('addressPostcode', new FormControl(controlValue))
    } else {
      this.createOrganisation.addControl('addressPostcode', new FormControl(null))
    }
    
  }
}

如果它符合您的要求,您可以使用它。

警告:

  1. 不要在模糊事件中更新标志。
  2. 如果在用户在输入框中输入时更新了标志,那么他将失去输入的焦点,因为控件将被更新。

在此处查看示例:https ://stackblitz.com/edit/updateoncontrol?file=src/app/app.component.ts


推荐阅读