Forms
Template Forms
Master Angular Template-Driven Forms, covering directives (ngModel, ngForm), validation states, submissions, and template setups.
1. Learning Objectives
In this lesson, you will master Angular template-driven forms. By the end of this topic, you will be able to:
- Explain the architecture of template-driven forms.
- Use
ngModelto bind individual form inputs. - Access form state values using template reference variables (
#myForm="ngForm"). - Inspect control validation states (dirty, touched, valid, invalid).
- Handle form submissions using the
ngSubmitevent listener.
2. Overview
Template-driven forms in Angular delegate form management to the HTML template. By using directives like ngModel, ngForm, and validation attributes (like required or email), you can manage simple forms directly in your HTML markup without writing complex TypeScript logic.
3. Why This Topic Matters
Template-driven forms are ideal for simple forms:
- Quick Prototyping: For simple screens (like login, newsletter signup, or contact forms), template-driven forms let you bind values and validate fields directly in HTML without configuring TypeScript form models.
- Control Validation States: Angular tracks control states (e.g. if the user clicked inside a field and then left, or typed text). Using these states, you can show error messages only when appropriate (e.g. after the user interacts with the input).
4. Real-World Analogy
Think of template-driven forms like **filling out a paper form at a doctor's office**:
- The Paper Form (HTML template): The physical form itself defines the layout and rules (e.g. "please write your email address in this specific box").
- The Clipboard (ngForm): The clipboard holds the form together. It tracks if any boxes are left blank, and prevents you from submitting the form to the receptionist until all required fields are filled out.
- The Receptionist (Component Class): The receptionist does not care how you write in the boxes; they only receive the completed form when you click submit.
5. Core Concepts
Template-driven forms rely on three main directives:
- ngModel: Binds a component property to a form input element. Requires a
nameattribute on the element to register it with the form. - ngForm: Angular automatically attaches this directive to all
<form>tags. It creates a top-levelFormGroupinstance to track form values and validation status. - Validation States: Angular applies CSS classes to inputs based on their state:
ng-touched/ng-untouched,ng-dirty/ng-pristine, andng-valid/ng-invalid.
| Control State Pair | CSS Class Applied | Meaning |
|---|---|---|
| pristine / dirty | .ng-pristine | .ng-dirty | Dirty indicates the user has typed in or modified the input value. |
| untouched / touched | .ng-untouched | .ng-touched | Touched indicates the user has clicked inside the field and then left (blurred). |
| valid / invalid | .ng-valid | .ng-invalid | Invalid indicates the input value fails its validation rules. |
6. Syntax & API Reference
Below is a template-driven form that uses template reference variables to show error messages:
7. Visual Diagram
This diagram displays how template-driven forms synchronize states with component classes:
8. Live Example — Full Working Code
Below is a newsletter registration form component that imports the FormsModule:
9. Interactive Playground
Try It Yourself Challenges:
- Add a
minlength="6"attribute validation rule to the password input and check if the form validation state updates. - Test what happens when you type text into the input field and click submit.
10. Common Mistakes
| Mistake | Why it happens | Wrong | Correct |
|---|---|---|---|
| Forgetting the name attribute on inputs | Forgetting to set the HTML name attribute on inputs when using ngModel. Angular requires the name attribute to register the control with the parent form. |
<input ngModel required /> |
<input name="username" ngModel required /> |
11. Best Practices
- Always set the name attribute: Set the HTML
nameattribute on all form controls that use thengModeldirective. - Use novalidate on form tags: Add the
novalidateattribute to<form>elements. This disables native browser validation tooltips, letting you display custom Angular validation error messages instead. - Reset forms after submission: Call
form.resetForm()after successful form submissions to clear input values and reset validation states (like returning fields to pristine).
12. Browser Compatibility/Requirements
Template-driven forms are compatible with all modern browsers. The novalidate attribute works consistently in all HTML5-compliant browsers.
13. Interview Questions
🟢 Q1: What does #myForm="ngForm" do in an Angular template-driven form?
Answer: It creates a template reference variable named myForm and binds it to the NgForm directive instance that Angular automatically attaches to the <form> tag. This allows you to check form state properties (like myForm.valid or myForm.value) directly in the HTML template.
14. Debugging Exercise
Identify and fix the compiler error in this template-driven form layout:
Diagnosis:
1. The form submission handler tries to pass the variable f, but f is not defined in the template. You must declare a template reference variable (e.g. #f="ngForm") on the <form> tag.
2. The input element uses ngModel, but is missing the required name attribute. Angular needs the name attribute to register the control with the parent form.
Fixed template markup:
15. Practice Exercises
Exercise 1: Create a simple contact form
Build a contact form containing name, email, and message inputs. Display validation errors for each field, and keep the submit button disabled until all inputs are valid.
16. Scenario-Based Challenge
The Legacy Form Validation Refactor:
An existing HTML page uses plain CSS and JavaScript to validate form inputs. Refactor the page to use Angular's template-driven forms. Bind input values, track control states, and display validation message divs based on the input's touched and invalid states.
17. Quick Quiz
Q1: Which directive must be added to a form input element to register it with the parent ngForm instance?
A) formControl
B) ngModel
C) ngControl
Answer: B — The ngModel directive registers input elements with the parent form instance (requires a name attribute).
18. Summary & Key Takeaways
- • Template-driven forms delegate form validation and control state management to the HTML template.
- • Use ngModel and the name attribute to register input elements and bind values.
- • Access validation states (like valid, invalid, touched) directly in templates using template reference variables.
19. Cheat Sheet
| Directive | Purpose |
|---|---|
#f="ngForm" |
Binds form data and validation states to a template reference variable. |