The resetForm method resets an NgForm controller’s validation status and returns the form to its original pristine state. It is useful after a valid submission, when the same form must accept another product. section 13.4.3
Reset after a successful submission
Pass the template’s NgForm reference to the submit handler. After validation succeeds, add the product, create a fresh model object, reset the form, and clear the submission flag: submitForm(form: NgForm) { this.formSubmitted = true; if (form.valid) { this.addProduct(this.newProduct); this.newProduct = new Product(); form.resetForm(); this.formSubmitted = false; } }
Listing 13.20. Enhancing the component in the component.ts file in the src/app folder
import { Component, computed, signal } from "@angular/core";
import { Model } from "./repository.model";
import { Product } from "./product.model";
import { NgModel, ValidationErrors, NgForm } from "@angular/forms";
@Component({
selector: "app",
templateUrl: "template.html"
})
export class ProductComponent {
private model: Model = new Model();
// ...statements omitted for brevity...
formSubmitted: boolean = false;
submitForm(form: NgForm) {
this.formSubmitted = true;
if (form.valid) {
this.addProduct(this.newProduct);
this.newProduct = new Product();
form.resetForm();
this.formSubmitted = false;
}
}
}
Inspect the complete component implementation showing validation, model replacement, resetForm invocation, and submission-state handling. section 13.4.3
