Angular2反应形式删除错误

Arm*_*yan 14 angular2-forms angular

我正在尝试将表单控件状态设置为有效

this.currencyForm.controls['currencyMaxSell'].setErrors({smallerThan: true})
Run Code Online (Sandbox Code Playgroud)

现在我要删除此错误.

kar*_*luS 11

其他解决方案似乎不起作用.只要errors属性不为null,看起来角度思维控制无效.

只要您想删除单个错误并留下其他错误,就无法手动执行此操作.下面的这个函数只会删除参数ale中指定的一个错误.它还将确保如果您删除错误,控件将变为有效.

// call it in validator function if control is valid
removeError(this.currencyForm.controls['currencyMaxSell'], 'smallerThan');

//this function removes single error
    function removeError(control: AbstractControl, error: string) {
      const err = control.errors; // get control errors
      if (err) {
        delete err[error]; // delete your own error
        if (!Object.keys(err).length) { // if no errors left
          control.setErrors(null); // set control errors to null making it VALID
        } else {
          control.setErrors(err); // controls got other errors so set them back
        }
      }
Run Code Online (Sandbox Code Playgroud)

随意编辑此问题,使其更具可读性.

免责声明:我在ANGULAR 6中测试过它


uni*_*rio 8

只需将错误对象中的值设置为null:

this.currencyForm.controls['currencyMaxSell'].setErrors({smallerThan: null})
Run Code Online (Sandbox Code Playgroud)

或者,如果要setErrors(null)根据注释中的建议从控件中删除所有验证.

  • 这是错的!如果你这样做,仍然`currencyForm.invalid`是真的 (18认同)
  • 这是不正确的...这里讨论https://github.com/angular/angular/issues/21564 (2认同)

Vah*_*hid 7

AFAIK,setErrors当您可以创建自定义验证器时,您真的不需要使用方法.您可以轻松地为formControl或formGroup创建自定义验证器,并且在验证器内只需要返回ValidatorFn,就不应该使用setErrors方法.

有关FormGroup的自定义验证器的更多信息,我建议您阅读本文解决了我的问题.

这是我的工作代码:

registerationForm = this.formBuilder.group({
  username: ['', [Validators.required, Validators.email]],
  passwords: this.formBuilder.group(
    {
      password: ['', Validators.required],
      confirmPassword: ['', Validators.required]
    },
    {
      validator: matchPassword
    }
  ),
  policyAgreement: ['', Validators.required]
});

// Outside my component:
const matchPassword = (group: FormGroup) => {
  const password = group.get('password').value;
  const confirmPassword = group.get('confirmPassword').value;
  return password != confirmPassword ? { matchPassword: true } : null;
};
Run Code Online (Sandbox Code Playgroud)

  • 当你想要在提交表单后设置从服务器返回的错误时,`setErrors`非常有用,我不确定在这些情况下是否可以使用自定义验证器. (3认同)

小智 5

要在执行手动验证时仅删除一个表单控件错误,请执行以下操作:

this.myFormGroup.get('myControl').setErrors({'myCustomError':null})
Run Code Online (Sandbox Code Playgroud)

这将仅更新指定错误的值,并且不会删除您可能已执行的任何先前验证,而不setErrors(null)会使控件的整个错误对象无效.

  • 对我来说,它使FormControl无效. (2认同)