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

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

我必须重置表单并进行验证。是否有任何方法可以将形式状态从ng-dirty重置为ng-pristine。


这是当前与Angular 4.1.0-5.1.3一起使用的方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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的内容如下:

在您的模板中,将您的表单发送到Submit函数:

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

在您的component.ts文件中,具有以下内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 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值将输出以下内容-请注意,它将重置所有值。

有效真假假真真假假

无效假真真假假真真


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

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

传递表单以提交或使用ViewChild观看根本不起作用,目前这对我来说已经足够了。


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

带有角材料的角6

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

然后

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@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();
}

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

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

1
2
3
4
private submitForm(formDirective): void {
    formDirective.resetForm();
    this.myForm.reset();
}


在更多当前版本中(以我的angular为2.4.8),这很容易:

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

1
2
3
4
5
private resetFormControlValidation(control: AbstractControl) {
    control.markAsPristine();
    control.markAsUntouched();
    control.updateValueAndValidity();
}

app.component.html

#formDirective="ngForm"并将formDirective传递给onSubmit方法对于重置诸如mat-error之类的错误样式至关重要。请检查#4190,以跟踪此bug并深入解释为什么需要它以及它在内部如何工作。

1
2
3
4
<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/材质9)导入的FormGroupDirective。要使表单为空,请调用this.contactForm.reset();,并且表单将为invalid,这很好。但是,您还需要重置不需要的验证器样式,这是另一种方法,即formDirective.resetForm();

通过不同的内置方法注意formDirectiveformData之间的区别。

1
2
3
4
5
6
7
8
9
10
11
12
13
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
}


目前似乎尚不支持。
我看到的一种解决方法是在提交后重新创建表单,这显然很麻烦而且很丑。

另请参阅

  • https://github.com/angular/angular/issues/6196
  • https://github.com/angular/angular/issues/4933
  • https://github.com/angular/angular/issues/5568
  • https://github.com/angular/angular/issues/4914


基于Benny Bottema的回答,我能够使用Angular 6中的resetForm()重置包含验证的表单。

1
2
3
4
5
6
7
8
9
10
class YourComponent {

   @ViewChild("yourForm")
   yourForm: NgForm;

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

此Angular 8中的解决方案对我来说是反应形式

命名您的表单,如下所示:

1
<form #regForm="ngForm">

使用ViewChild

创建UI表单的对象

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

在提交呼叫后使用此功能。

1
this.myForm.resetForm();

提交了错误的验证

1
this.submitted = false;


这在Angular 5中使用模板驱动的形式对我有效(不适用于反应性形式)

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

这将重置表单值和验证。


角反应形式

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

如果您正在使用Angular Material并使用<mat-error>,那么它对我来说唯一有效的方法就是此方法。
您必须使用FormGroupDirective。

1
2
3
4
5
@ViewChild(FormGroupDirective) formDirective: FormGroupDirective;

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

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

我在Angular btw中使用模板驱动形式。


在最新的Angular版本中,您只需要运行this.form.reset()(它将所有内容标记为原始且未更改,并且将所有内容标记为内幕),然后更新所有子窗体控件/组/数组的值和有效性。铅>

不幸的是,至少在目前,没有直接遍历子控件的嵌套控件没有直接方法。


我最近考虑了这一点,因为目前(2016年5月)目前尚未在Angular2中构建任何架构。

考虑到用户不能输入'undefined'或'null',并且验证主要用于向用户显示格式错误,然后只需将控制值重置为Null

1
myControl.updateValue(null);

仅通过添加

决定在UI中显示控件错误时,就需要添加此条件

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

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

希望这会有所帮助。


如果您使用模型驱动的表单(即ngFormModel),则在提交后再次定义controlGroup即可解决此问题。请参阅此链接


Angular 8表单重置验证错误

创建表单:

1
2
3
 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-.]+$')]]});

重置形式:

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