Reset Form in angular 5 after submit

10,098

Solution 1

HTML component

Add #f="ngForm" in the form tag as you'have already added

 <form class="form-horizontal" name="form" (ngSubmit)="!f.form.invalid
    && staffDetails(model)" #f="ngForm" novalidate>
   <!-- form inputs -->
 </form> <!-- form closed>

Logic Component i.e TS File

import { ViewChild } from '@angular/core';

  @ViewChild('f') myForm; //feth reference of form using ViewChild property

After declare, we can reset the form using reset function

staffDetails(data){

     this.myForm.resetForm(); //now the form is reset
}

Working Module for this functionality:- https://angular-xtzntk.stackblitz.io/

Solution 2

A reset will clear the entire form and move its state back to pristine (no validations fired), whereas a resetForm will just clear the values and not change the state. Source

depending on what needs to be done

html file

<form #f="ngForm" (ngSubmit)="onSubmit(f)">

ts file

protected onSubmit(f: NgForm): void {

        // code here

        f.resetForm(); or f.reset();
    }

pass the form instance defined as f to the submit function and do the reset Source

Solution 3

Use reset()

Try this

this.myform.reset();

Solution 4

As you are using template driven forms try this.

Use (ngSubmit) event to handle the form submit event. And pass the form as a parameter to the event handler. (ngSubmit)="onFormSubmit(f)

In your component.html

 <form class="form-horizontal" name="form" (ngSubmit)="onFormSubmit(f)" #f="ngForm" novalidate>

In your component.ts

public onFormSubmit(ngForm: ngForm): void {
   // !f.form.invalid && staffDetails(model)
   ngForm.form.reset();
}
Share:
10,098
Rohit Bhadra
Author by

Rohit Bhadra

Updated on December 06, 2022

Comments

  • Rohit Bhadra
    Rohit Bhadra 11 months
     <form class="form-horizontal" name="form" (ngSubmit)="!f.form.invalid && staffDetails(model)" #f="ngForm" novalidate>
    
    
     <div class="form-group"><button [disabled]="f.invalid" *ngIf ="buttonSave" class="btn btn-info">Save</button></div>
    

    after click submit button without refreshing the page when resubmit the values didn't fetch

    • Pardeep Jain
      Pardeep Jain over 5 years
      What are you trying to ask?
    • Robert
      Robert over 5 years
      Yes your question not clear
  • Rohit Bhadra
    Rohit Bhadra over 5 years
    but myform only using on form group i m not using that
  • Rohit Bhadra
    Rohit Bhadra over 5 years
    i used that but in resubmit the values are not submitted
  • Krishna
    Krishna over 5 years
    Where is your re submit button. Can you please put a full code snippet what you want to achieve so that we can undersatnd your problem better