Add a reference to the ngForm
directive in your html code and this gives you access to the form, so you can use .resetForm()
.
<form #myForm="ngForm" (ngSubmit)="addPost(); myForm.resetForm()"> ... </form>
...Or pass the form to a function:
<form #myForm="ngForm" (ngSubmit)="addPost(myForm)"> ... </form>
addPost(form: NgForm){
this.newPost = {
title: this.title,
body: this.body
}
this._postService.addPost(this.newPost);
form.resetForm(); // or form.reset();
}
The difference between resetForm
and reset
is that the former will clear the form fields as well as any validation, while the later will only clear the fields. Use resetForm after the form is validated and submitted, otherwise use reset.
Adding another example for people who can't get the above to work.
With button press:
<form #heroForm="ngForm">
...
<button type="button" class="btn btn-default" (click)="newHero(); heroForm.resetForm()">New Hero</button>
</form>
Same thing applies above, you can also choose to pass the form to the newHero
function.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…