NgForm is an Angular directive and form controller that represents an HTML form, exposes its validation state, and coordinates submission handling. Create a template reference with #form="ngForm", then pass that object to the component through (ngSubmit). section 6.5.2 section 13.4.3
Use the NgForm object to manage form-wide behavior:
- Check form.valid before saving or adding the submitted model object. section 6.5.2 section 13.4.3
- Read form.invalid to display a summary after the user attempts submission. section 13.4.3
- Call resetForm() to restore validation state and return the form to its pristine state. section 13.4.3
- Inspect form.controls to collect validation errors from individual controls. section 13.4.3
Validate before completing an order
The checkout form declares #form="ngForm" and binds submission to submitOrder(form). The component marks submission as attempted, saves the Order only when form.valid is true, then clears the order and resets the completion state. Required inputs expose invalid or valid states through Angular’s validation classes, allowing the template and CSS to provide feedback.
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 method that receives NgForm, gates model updates on form.valid, and calls resetForm(). section 13.4.3
