Simplicity in Capture: Mastering Template-Driven Forms
Angular offers two distinct approaches to handling user input: Reactive Forms and **Template-Driven Forms**. While Reactive forms are often lauded for their scalability and testability, Template-Driven forms remain the go-to solution for simple to moderately complex forms due to their simplicity and declarative nature. You define the logic right where you define the layout: in the HTML.
The Core Trinity: Module, Directive, Reference
To make template-driven forms work, you must understand the three pillars that hold the structure together:
- FormsModule: Without importing this in your `AppModule` (or feature module), none of the directives will work. It is the key that unlocks the engine.
- ngModel: This is the bridge. Placed on an input, it tells Angular, "Watch this field." It handles the data synchronization between your view (HTML) and your model (Class).
- ngForm: Angular automatically attaches this directive to any
<form>tag when `FormsModule` is active. It silently tracks the aggregate state of every control inside it.
The Magic of Template Reference Variables
Perhaps the most powerful feature is the ability to extract the entire form state into a local variable using the syntax #myForm="ngForm". This variable exposes properties like:
State Properties
- valid: True if all controls pass validation.
- dirty: True if the user has modified a value.
- touched: True if the user has blurred a field.
Usage Example
<button [disabled]="!myForm.valid">
Submit
</button>Disabling the button until the form is valid.
Two-Way Binding Syntax
The famous "Banana in a Box" syntax [(ngModel)]="user.name" is syntactic sugar. It combines a property binding `[ngModel]` (writing data to the view) and an event binding `(ngModelChange)` (reading data from the view). This allows for real-time synchronization between your TypeScript code and the user's input.
Pro Tip: Always provide a `name` attribute when using `ngModel` inside a <form>. Angular uses the `name` attribute to register the control with the parent `ngForm` directive. Without it, you'll get a console error.