在reset()表单之后出现角度验证消息

时间:2018-11-25 21:33:06

标签: angular forms angular-reactive-forms angular-validation

我尝试在调用reset()之后使表格变得清晰而没有验证错误消息。

我的表单在加载时看起来很干净,这是可以预期的: form as when the page loaded, no validation errors 但是,如果用户按下注册按钮,并且出现错误,我将触发form.reset()方法。我希望表格看起来像上面的图片,因为触摸,原始,肮脏的道具都与表格初次加载时一样。 而是清除了值,但显示了验证错误。 form with validation errors 谁能帮我将其恢复为初始状态,是否显示无验证错误的清晰表格? 这是一种反应形式。如果您需要更多信息,请与我们联系。谢谢!

4 个答案:

答案 0 :(得分:5)

您似乎正在使用Angular Materials。 如果是这样,还必须重设FormGroupDirective,仅重设FormGroup是不够的。

private registerForm(fData: any,formDirective: FormGroupDirective): void {
    formDirective.resetForm();
    this.RegForm.reset();
}

<form [formGroup]="RegForm" #formDirective="ngForm" 
   (ngSubmit)="registerForm(RegForm,formDirective)">

答案 1 :(得分:0)

您是否正在使用类似的内容?

// Reactive Form

constructor(private _builder:FormBuilder) {
    this.createForm();
}

createForm() {
    this.form = this._builder.group({
        key: this.value,
    });
}

// Option 1
resetForm() {
    this.form.reset();
}

// Option 2 - create form again
resetForm() {
    this.createForm()
}

// Template Form

---- HTML ----
<form #myForm="ngForm"></form>

---- TS ----
@ViewChild('myForm') myForm;

resetForm() {
   if (this.myForm) {
      this.myForm.reset();
   }
}

答案 2 :(得分:0)

static resetForm(formGroup: FormGroup) {
    let control: AbstractControl = null;
    formGroup.reset();
    formGroup.markAsUntouched();
    Object.keys(formGroup.controls).forEach((name) => {
      control = formGroup.controls[name];
      control.setErrors(null);
    });
  }

答案 3 :(得分:0)

您可以使用表单的方法.markAsPristine()重设验证:

this.RegForm.reset();
this.RegForm.markAsPristine();
相关问题