繁体   English   中英

如何清除角度控件中的错误

[英]How to clear errors in angular controls

如何在 angular 中设置自定义错误非常清楚:

this.form.controls['field'].setErrors({same:true});

但目前尚不清楚如何删除它。 有人知道怎么做吗? 任何替代方案?

只需将错误设置为空

this.form.controls['field'].setErrors(null);

this.form.controls['field'].updateValueAndValidity();

这是方法文档:

/**
  * Re-calculates the value and validation status of the control.
  *
  * By default, it will also update the value and validity of its 
 ancestors.
  */
 updateValueAndValidity({onlySelf, emitEvent}: {onlySelf?: boolean, emitEvent?: boolean} = {}):  void {... }

当您想要删除自定义错误时,您可以使用以下内容:

delete this.form.controls['field'].errors['same']

您可能需要/想要在此之后更新有效性:

this.form.controls['field'].updateValueAndValidity();

您可以使用以下行删除自定义错误。

this.form.controls['field'].updateValueAndValidity();

您可以使用下面提到的方法并传递控件名称,键表示错误名称和值将分别为true或null来设置或删除控件中的错误。

errorInFields(control: AbstractControl,key,value){
let errors  = control.errors;
if(!errors){
  if(value == null){
    control.setErrors(null);
  }else{
    let error = {};
    error[key] = value;
    control.setErrors(error);
  }
}else{

  if(value == null){
    if(errors.hasOwnProperty(key)){
      delete errors[key];
    }
    let errorsKey = Object.getOwnPropertyNames(errors);;
    if(errorsKey.length <= 0){
      control.setErrors(null);
    }else{
      control.setErrors(errors);
    }
  }else{
    errors[key] = value;
    control.setErrors(errors);
  }
}}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM