liveBook · Manning

resetForm method

As explained in Pro Angular 16

The resetForm method resets an Angular form controller's validation state and returns the form to its original pristine state.

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

How Pro Angular 16 covers it

How deep it goes
Explains the method’s state-reset effect and demonstrates its placement in a submit handler, without detailing framework internals.
Examples
Demonstrates resetting a product-entry form after adding a valid product and replacing the bound product object.
What it assumes
Assumes familiarity with Angular forms, NgForm, template references, and form submission handlers.
What you can do after
Operate resetForm in an Angular submit handler to restore a reusable form’s validation and pristine state.
How it connects
Connects resetForm with NgForm, form validation, ngSubmit, pristine state, and template references.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro Angular 16. The section links point to the parts of the book it draws on.