Resetting template driven forms in angular 2 (mode

2019-02-22 13:33发布

问题:

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?

回答1:

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



回答2:

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


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


回答3:

This worked for me:

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


回答4:

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

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