如何在 ANGULAR 2 中提交表单时重置表单验证

How to reset form validation on submission of the form in ANGULAR 2

我必须在验证的同时重置我的表单。有什么方法可以将表单的状态从 ng-dirty 重置为 ng-pristine。

似乎还没有对此的支持。 我看到的一种解决方法是在提交后重新创建表单,这显然很麻烦而且很难看。

另见

如果你使用model-driven表单,即ngFormModel,提交后再次定义controlGroup将解决this.Refer这个link

我最近考虑过这个,因为目前(2016 年 5 月)Angular2 还没有为此构建任何架构。

考虑到用户无法输入 'undefined' 或 'null' 并且验证主要用于向用户显示表单错误然后将控件值重置为 Null

myControl.updateValue(null);

当决定在 UI 中显示控制错误时,您需要添加此条件,只需添加

if (myControl.value !== undefined && myControl.value !== null) {
   //then there is reason to display an error
}

(此检查是因为 Validators.Required 将空白内容视为有效)

希望对您有所帮助。

我在 RC.5 中这样做,我在模板中定义我的表单元素。

<form (ngSubmit)="submit(); form.reset()" #form="ngForm">

通过表单提交或使用 ViewChild 观看根本不起作用,这对我来说已经足够了。

在更新的版本中(Angular 2.4.8 在我的例子中)很简单:

将控件标记为 prestine,因此再次有效。

private resetFormControlValidation(control: AbstractControl) {
    control.markAsPristine();
    control.markAsUntouched();
    control.updateValueAndValidity();
}

以下是它目前在 Angular 4.1.0 - 5.1.3 中的工作方式:

class YourComponent {
    @ViewChild("yourForm")
    yourForm: NgForm;


    onSubmit(): void {
        doYourThing();

        // yourForm.reset(), yourForm.resetForm() don't work, but this does:
        this.yourForm.form.markAsPristine();
        this.yourForm.form.markAsUntouched();
        this.yourForm.form.updateValueAndValidity();
    }
}

from.resetForm()

我几乎尝试了所有方法,我发现唯一真正将 form.submitted 重置为 false 的是:

在您的模板中,将表单发送到提交功能:

<form name="form" class="form-horizontal" (ngSubmit)="f.form.valid && submit(f)" #f="ngForm" novalidate>

在您的 component.ts 文件中,包含以下内容:

// import NgForm
import { NgForm } from '@angular/forms';

// get the passed in variable from the html file
submit(myForm: NgForm): void {

    console.log(myForm.form.status, myForm.form.dirty, myForm.form.pristine, myForm.form.untouched, myForm.submitted, myForm.dirty, myForm.pristine, myForm.untouched);

    // This is the key!
    myForm.resetForm();

    console.log(myForm.form.status, myForm.form.dirty, myForm.form.pristine, myForm.form.untouched, myForm.submitted, myForm.dirty, myForm.pristine, myForm.untouched);


}

console.log 值输出以下内容 - 请注意它会重置所有值。

有效 true false false true true false false

无效 false true true false false true

这在 Angular 5 中使用模板驱动表单对我有用(它不适用于反应式表单)

<form #myForm = "ngForm" (submit)="callMyAPI(); myForm.resetForm()">

这会重置表单值和验证。

开始构建,我能够在 Angular 6 中使用 resetForm() 重置包括验证在内的表单。

class YourComponent {

   @ViewChild("yourForm")
   yourForm: NgForm;

    onSubmit(): void {
     doYourThing();
     this.yourForm.resetForm();
    }
}

在此感谢大家的回答。他们给我指明了正确的方向。

Angular 6 与 Angular Material

<form #myForm="ngForm" [formGroup]="formGroup" (ngSubmit)="submit()">

然后

@ViewChild('myForm') myForm: NgForm;
formGroup = new FormGroup({...});
submit() {
  if (this.formGroup.pristine ||
  this.formGroup.untouched ||
  !this.formGroup.valid
) {
    return;
  }

  .... do with form data

  this.formGroup.reset();
  this.myForm.resetForm();
}

如果您正在使用 Angular Material 并使用 <mat-error>,唯一对我有用的方法就是这个。 你必须使用 FormGroupDirective。

@ViewChild(FormGroupDirective) formDirective: FormGroupDirective;

submitBtnClick() {
  this.formDirective.resetForm();
}

Angular 8 中的这个解决方案在 Reactive Forms 中对我有用

像这样命名您的表单

<form #regForm="ngForm">

使用 ViewChild 创建 UI 窗体的对象

@ViewChild('regForm', {static: false}) myForm: NgForm;

在提交调用后使用它。

this.myForm.resetForm();

您的验证提交错误

this.submitted = false; 

Angular 8 表单重置验证错误

创建表单:

 this.userForm = this.formBuilder.group({
  firstName: ['', [Validators.required, Validators.minLength(2)]],
  email: ['', [Validators.required, Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')]]});

重置表格:

this.userForm.reset();
this.userForm.controls.userEmail.setErrors(null);

app.component.html

#formDirective="ngForm" 并将 formDirective 传递给 onSubmit 方法对于重置 mat-error 等错误样式至关重要。检查 #4190 to follow this bug and in-depth explanation .

<form [formGroup]="contactForm" (ngSubmit)="onSubmit(contactForm.value, formDirective)" #formDirective="ngForm"> 
  <!-- Your input elements... -->
  <button [disabled]="!contactForm.valid">Submit</button>
</form>

app.component.ts

记住您需要从 @angular/forms (Angular/Material 9) 导入的 FormGroupDirective。要使表单为空,调用 this.contactForm.reset(); 并且表单将为 invalid,没问题。但是,您还需要重置不需要的验证器样式,这是一种 不同的 方法,即 formDirective.resetForm();.

注意 formDirectiveformData 之间的区别及其不同的内置方法。

import { FormGroupDirective } from '@angular/forms';

public contactForm: FormGroup = this.formBuilder.group({
  // Your input elements...
});

public onSubmit(
  formData: FormGroup,
  formDirective: FormGroupDirective
): void {
  this.contactForm.reset(); // Reset form data
  formDirective.resetForm(); // Reset the ugly validators
}

使用 YourformName.reset() 重置时,我遇到了验证错误问题。 所以在你的 .ts 文件中使用 YourformName.resetForm() 。它现在工作正常。

我在 Angular 中使用模板驱动的表单。

在最新的 Angular 版本中,您只需要 运行 this.form.reset()它会将所有内容标记为原始且未受影响,以及所有内容) 然后 update value and validity for all the child form controls/groups/arrays.

不幸的是,对于没有手动遍历子项的嵌套控件,至少目前没有直接的方法。

<form #formDirective="ngForm" (ngSubmit)="submitForm(formDirective)">

然后在您的组件 class 中调用 formDirective.resetForm():

private submitForm(formDirective): void {
    formDirective.resetForm();
    this.myForm.reset();
}

Angular 反应形式

onCancel(): void {
    this.registrationForm.reset();
    this.registrationForm.controls['name'].setErrors(null);
    this.registrationForm.controls['email'].setErrors(null);
  }

只需遍历表单控件并使它们保持原始状态

     (Object as any).values(this.mainForm.form.controls).forEach((control: FormControl) => {
        control.markAsUntouched();
        control.markAsPristine();
      });

确保您的按钮类型 = button !!!

默认情况下 html 按钮获取类型="提交"