簡體   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