What are Template-Driven Forms?
Template-driven forms rely on directives in the template (HTML) to create and manage the underlying form model. As an Engineering Manager, you might choose this approach for simple forms, such as a basic 'Contact Us' page or a quick search filter. It is heavily inspired by AngularJS (1.x) and uses two-way data binding to keep the component's variables in sync with the input fields.
- The Role of ngModel
The ngModel directive is the star of template-driven forms. It creates a FormControl instance from a domain model and binds it to a form control element. This allows for 'Banana-in-a-box' syntax [(ngModel)] which ensures that if the user types in the box, the variable updates, and vice versa.
- Using the NgForm Directive
Angular automatically attaches the NgForm directive to any <form> tag. You can use a Template Reference Variable (like #projectForm) to export a reference to the NgForm instance, allowing you to check the overall validity of the form or reset it.
- Validation in the Template
In this approach, validation is added using standard HTML attributes like required, minlength, and pattern. Angular recognizes these attributes and uses them to set the validation status of the associated FormControl.
Comparison: Template-Driven vs. Reactive
| Feature | Template-Driven | Reactive |
|---|---|---|
| Logic Location | Template (HTML) | Component (TypeScript) |
| Data Binding | Two-way (ngModel) | One-way (Observable) |
| Testing | Requires DOM (Integration) | Logic only (Unit) |
| Complexity | Best for simple forms | Best for complex forms |
| Model Management | Implicit / Asynchronous | Explicit / Synchronous |