Skip to main content
Template-driven forms use directives in templates to create and manipulate the underlying form object model. They rely on two-way data binding with 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
For more complex scenarios, consider reactive forms.

Setting Up Template-Driven Forms

Import FormsModule in your component or module:

Basic ngModel Usage

The ngModel 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 using ngModel 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

email

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

Use ngModelGroup to create sub-groups within a form:
packages/forms/src/directives/ng_model_group.ts

ngModelOptions

Customize how ngModel works with ngModelOptions:

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

Template-driven forms are perfect for simple forms with basic validation.
Get forms up and running quickly without much setup.
If your team prefers working in templates rather than component classes.
Template-driven forms are similar to AngularJS forms, easing migration.

Best Practices

Always provide a name attribute when using ngModel within a <form> tag.
Use template reference variables to access form and control state in templates.
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