ngModel to track changes and update the data model.
When to Use Template-Driven Forms
Template-driven forms are ideal for:- Simple forms with minimal validation
- Forms that closely mirror the view structure
- Quick prototypes and small applications
- Scenarios where you prefer working in templates over component classes
Setting Up Template-Driven Forms
ImportFormsModule in your component or module:
Basic ngModel Usage
ThengModel directive creates a FormControl instance and binds it to a form control element.
One-Way Binding
Two-Way Binding
Use banana-in-a-box syntax[(ngModel)] for two-way data binding:
packages/forms/src/directives/ng_model.ts
Working with Forms
When usingngModel within a <form> tag, provide a name attribute so the control can be registered with the parent form.
Basic Form Example
packages/forms/src/directives/ng_model.ts
Accessing Form State
You can export the form directive into a local template variable using#varName="ngForm":
Accessing Individual Controls
Export individual controls to access their state:packages/forms/src/directives/ng_model.ts
Form Validation
Template-driven forms use directives for validation:Built-in Validation Directives
required
Requires a non-empty value
Validates email format
minlength
Minimum length for strings/arrays
maxlength
Maximum length for strings/arrays
min
Minimum value for numbers
max
Maximum value for numbers
pattern
Validates against a regex pattern
Grouped Controls
UsengModelGroup to create sub-groups within a form:
packages/forms/src/directives/ng_model_group.ts
ngModelOptions
Customize how ngModel works withngModelOptions:
Standalone Controls
Create a control that doesn’t register with the parent form:Update On Blur or Submit
Control when the model updates:Custom Name
Provide a name through options instead of the name attribute:Handling Different Input Types
Text Inputs
Checkboxes
Radio Buttons
Select Dropdowns
Multiple Select
Template-Driven Forms vs Reactive Forms
When to Choose Template-Driven Forms
Simple forms
Simple forms
Template-driven forms are perfect for simple forms with basic validation.
Quick prototypes
Quick prototypes
Get forms up and running quickly without much setup.
Template-centric approach
Template-centric approach
If your team prefers working in templates rather than component classes.
Migration from AngularJS
Migration from AngularJS
Template-driven forms are similar to AngularJS forms, easing migration.
Best Practices
For complex forms with dynamic controls or extensive validation logic, consider reactive forms.
Next Steps
Form Validation
Learn about validation in template-driven forms
Reactive Forms
Explore reactive forms for more complex scenarios
