Bind `(ngSubmit)` on a form to run a component expression when the form is submitted. It handles the form’s submit event, so one binding can handle submission instead of click bindings on individual buttons. It does not, by itself, decide whether the form data is valid. section 13.4.2 section 13.4.3
Submit a product form
Start with `<form (ngSubmit)="addProduct(newProduct)">`. Inside it, bind a named input with `[(ngModel)]="newProduct.name"`, apply `required`, `minlength="5"`, and `pattern="^[A-Za-z ]+$"`, and use a button with `type="submit"`. Submitting calls `addProduct` with the current product. Keep the input inside the form: Angular’s form validation requires a form element. section 13.4.2
Check the whole form before adding the product
Change the opening tag to `<form #form="ngForm" (ngSubmit)="submitForm(form)">`. The `ngForm` reference gives the handler access to whole-form validation. In `submitForm(form: NgForm)`, set `formSubmitted = true`; if `form.valid`, add the product, replace `newProduct` with a fresh `Product`, call `form.resetForm()`, and clear `formSubmitted`. If the form is invalid, keep the data and use `formSubmitted && form.invalid` to show a warning. Field messages can appear after submission even when a field has not been edited. section 13.4.3
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;
}
}
}
The component listing shows the complete `submitForm` method, including its validity check and successful-submit reset. section 13.4.3
