VOOZH about

URL: https://www.geeksforgeeks.org/angular-js/how-to-clear-form-after-submission-in-angular-2/

⇱ How to clear form after submission in Angular 2? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to clear form after submission in Angular 2?

Last Updated : 9 Jun, 2020

In Angular 2, they are two types of forms:

  • Template-driven forms.
  • Reactive forms.
In template-driven forms, most of the content will be populated in .html file.
In Reactive forms, most of the functionalities and content will be performed in .ts file. The main advantage of reactive forms is, we can create custom validations and the second pivotal advantage is when we are performing unit testing, as the HTML code will be clean, it is more feasible to compose unit tests.
Resetting a form in template-driven approach:

In template driven approach, we need to import NgForm from '@angular/forms' and we use [(ngModel)] directive for two way data-binding and we should also import FormsModule from '@angular/forms' in app.module.ts file. In below line the input format is present. In addition to it, when we mention ngModel directive then we need to add name attribute to the input type.

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

In Reactive forms, we need to import FormGroup from '@angular/forms'.

After importing the above-mentioned modules in the respective approach, angular forms module provides an inbuilt method called reset(). We can use the method and we can reset the form. 
 

Example: .html file Example: .ts file

Resetting a form in Reactive forms:

Example: .html file Example: .ts file

Output:

👁 Image

After submitting the form, the output would be:

👁 Image
Comment
Article Tags:

Explore