如何在不重设角度的情况下重设验证错误?

时间:2019-04-20 19:02:25

标签: angular forms

我有一个角度模板驱动形式。我想重设所有验证错误,并使其不被更改而不重置​​表单。 如何做到这一点? 我尝试了以下方法

onAdd(form: NgForm) {

form.form.markAsPristine();
form.form.markAsUntouched();

}

但这不起作用。

链接:-https://stackblitz.com/edit/angular-ezixd4

当前行为:- 当我单击以提交空白表格时,所有字段都标记有错误,而当我单击add时,它会添加该字段,但上述功能不会删除错误消息。

预期的行为:- 当我单击以提交空白表格时,所有字段都标记有错误,当我单击add时,它将添加该字段,并且应该删除该窗体(或添加的文件)中的错误消息。

在此表单中,我要使用add Button添加输入字段,并且希望在用户有机会与表单进行交互之前清除所有错误消息。

8 个答案:

答案 0 :(得分:2)

对于 Angular Material,您需要定义 FoemGroupDirective 以及 FormGroupFormControl

@ViewChild(FormGroupDirective) formGroupDirective: FormGroupDirective;

import { FormGroup, FormControl, FormGroupDirective } from '@angular/forms';

在 onSubmit 方法中使用响应式表单重置重置 FoemGroupDirective

this.formGroupDirective.resetForm();
<br>
this.form.reset();

如果上述FoemGroupDirective重置不起作用,请尝试超时0秒

setTimeout(() => this.formGroupDirective.resetForm(), 0);

答案 1 :(得分:1)

您可以遍历每个必填字段,并在将null传递给它们的同时调用它们的setErrors方法:

YOUR_FORM.controls.YOUR_FIELD_NAME.setErrors(null);

例如,当您有一个usernamepassword字段时:

this.loginForm.controls.username.setErrors(null);
this.loginForm.controls.password.setErrors(null);

希望这会有所帮助!

答案 2 :(得分:1)

mat-input-invalid部分取决于表单的submitted状态。因此,当您提交表单时,submitted属性将切换为true。 markAsPristine()markAsUntouched()不会重置submitted标志,因此错误仍然显示。我看到两种可能性。一种快速而又肮脏的方法,当我测试似乎可以在您的情况下使用。我不能保证在所有情况下都可以,但是您可以尝试一下,看看它是否可以工作。也就是说,您呼叫resetForm(),它确实重置了submitted属性。但是,是的,您希望保留设置的值。因此,我们在重置中传递了表单当前状态的值:

onAdd(form: NgForm) {
  this.specification.push(++this.num);
  form.resetForm(form.value);  
}

DEMO

所以这是一种肮脏的方式,一种更受控制的方式是使用docs中提到的ErrorStateMatcher。这样,您可以选择何时显示错误消息。

答案 3 :(得分:1)

确保在表单部分内没有按钮。 def convertsgp(x): if x <= 99: y = 'Nominal' elif x <= 349: y = 'Threshold 1' elif x <= 1399: y = 'Threshold 2' elif x > 1400: y = 'Threshold 3' return y mydict = {'Singapore': convertsgp } for i in list(mydict.keys()): df.loc[(df['Country']== i, 'Threshold Level'] = mydict [i](df['LocalCurrency']) 按钮应位于该部分之外。

答案 4 :(得分:1)

 resetForm() {
    this.myFormGroup.reset();
    this.myFormGroup.setErrors(null); // could be removed
    this.myFormGroup.updateValueAndValidity();
  } 

答案 5 :(得分:0)

您可以使用更通用的方式做到这一点:

reset(formGroup: FormGroup) {
   Object.keys(formGroup.controls).forEach(
      field => {
         formGroup.get(field).setErrors(null);
      }
    );
}
...
this.reset(yourForm);
...

答案 6 :(得分:0)

这终于对我有用:

this.form.reset();
Object.keys(this.form.controls).forEach(key => {
    this.form.get(key).setErrors(null) ;
});

答案 7 :(得分:0)

我必须这样做,设置一个超时时间,以便单击取消按钮后,单击按钮之前的模糊事件不会得到处理:

let timeout = setTimeout(function() {
  Object.keys(originalValues).forEach(controlName => {
    let control =that.getControl(controlName);
    control.setValue(originalValues[controlName]);
    control.markAsUntouched();
    control.setErrors(null);
    control.markAsPristine();
  });
  this.setControlState(formName);
  clearTimeout(timeout);
}, 10);
相关问题