Angular Reactive forms : how to reset form state and keep values after submit

前端 未结 7 1750
逝去的感伤
逝去的感伤 2020-12-29 18:42

In an Angular reactive form. How to reset only the state of form after successful submit?

Here is the process:

  • Create the form and
相关标签:
7条回答
  • 2020-12-29 19:13

    Some time this.myForm.reset(this.myForm.value); may not reset to initial values So it is better to create a separate function to initialize the form and call it in ngOnInit() and before call this.myForm.reset(this.myForm.value);

    ngOnInit(){
      myFormValues();
    }
    
    myFormValues() {
      this.myForm= this.fb.group({
          id: ['', Validators.required],
          name: ['', Validators.required],
        });
    }
    
    submitForm() {
      // save data
      myFormValues();
      this.myForm.reset(this.myForm.value)
    }
    
    0 讨论(0)
  • 2020-12-29 19:14

    That's pretty much easy:

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

    This resets the form metadata and the form is pristine again

    0 讨论(0)
  • 2020-12-29 19:14

    For reactive forms what worked for me when using angular 7: was to use template-driven form and pass it via the form submit handler like so

    // component.html
     <form #f="ngForm" [formGroup]="form" (ngSubmit)="onSubmit(f)" novalidate>
     ....
    </form>
    
    
    // component.ts
    
    onSubmit(form: NgForm) {
    
    // reset form here
     form.form.markAsPristine();
     form.resetForm();
    }
    
    

    It will reset the form and the submitted state to default.

    0 讨论(0)
  • 2020-12-29 19:17

    Adding a another answers, if you have a disabled input in your form, use getRawValue() as a parameter of ngForm.resetForm(). See the sample:

    in HTML:

    <form
      (ngSubmit)="formSubmit(myForm)"
      #myForm="ngForm"
    >
        ...
    </form>
    

    in .TS:

    formSubmit(myForm: NgForm) {
       myForm.resetForm(myForm.form.getRawValue());
    }
    
    0 讨论(0)
  • 2020-12-29 19:24

    04-06-2020: Ionic 5+ and Angular 9+

    Just a single line. i.e. this.form.reset();

    Resets the FormGroup, marks all descendants are marked pristine and untouched, and the value of all descendants to null.

     form: FormGroup;
    
     constructor(private formBuilder: FormBuilder, ) { }
    
      resetTheForm(): void {
        this.form.reset();
      }
    
    0 讨论(0)
  • 2020-12-29 19:27

    The solution of @smnbbrv works pretty well.

    You can also provide your actual form value to reset() method.

    Given the fact myReactiveForm is a Reactive form in your component. After successful submit of your form (by calling a service for example), then your can do:

    this.myReactiveForm.reset(this.myReactiveForm.value);
    

    It will reset the form and set the "new" form values to the same value you form had.

    This method can be see within Tour of Hero example Official Angular.io doc

    0 讨论(0)
提交回复
热议问题