8

How do we reset the controls with validation states of Template driven forms in angular 2? I know that controls can be reset by setting model values to which they are bound to. But what about the validation states(pristine, dirty etc..)?

I tried something like this:

<form (ngSubmit)="onSubmit(playlistForm)" #playlistForm="ngForm">
// Some code here...
</form>

And in controller,

onSubmit(playlistForm: any) {
// ...
  playlistForm.form.reset();
}

But in above seems to actually redirect to the '' And I get error below:

EXCEPTION: Error: Uncaught (in promise): Error: Cannot match any routes: '' 

So how do I do what I want?

rahulserver
  • 10,411
  • 24
  • 90
  • 164

6 Answers6

15

Both of these worked for me:

playlistForm.reset();
playlistForm.resetForm(); // I think this is the one to use

Angular docs have resetForm() only https://angular.io/docs/ts/latest/api/forms/index/NgForm-directive.html

4
<form (ngSubmit)="onSubmit(playlistForm)" #playlistForm="ngForm">
// Some code here...
</form>


onSubmit(playlistForm: ngForm) {
// ...
  playlistForm.form.reset();
}
Suraj Khanal
  • 498
  • 8
  • 26
4

This worked for me:

<form (ngSubmit)="onSubmit(playlistForm);playlistForm.reset()" #playlistForm="ngForm">
    // Some code here...
</form>
Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79
3
form.resetForm(); 

This also resets the validation states of the form, unlike form.reset(). Works with template-driven and reactive approaches.

Samuel Mutemi
  • 358
  • 3
  • 7
  • This doesn't seem to be a function anymore. – DigiBanks99 Apr 15 '21 at 13:41
  • It is. I was using `@angular/forms: 8.0.0` when this answer was posted. I'm using `@angular/forms: 11.2.11` and `form.resetForm()` is currently available as a method in the class NgForm in the stated versions and the versions in between as far as I can tell. – Samuel Mutemi May 18 '21 at 08:04
0

I used native element reference in .ts and called form later cleared the form data once submitted using reset method

-1

This worked for me onClear() is additional callback I needed for some additional tasks.

<button type="reset" (click)="onClear()">Clear</button>
Rvk
  • 1
  • 1