Sub topic 1
How template-driven forms work and when to use them
Prerequisites
This chapter assumes you already know the following:
- Basic TypeScript classes and types.
- Angular components and templates, including standalone components and the
importsarray. - Angular template syntax: property binding, event binding, and template reference variables.
- Basic HTML form elements and validation attributes such as
requiredandminlength.
You do not need any prior experience with Angular's forms package. This chapter gives you the working model. Later chapters cover each piece in detail.
Two ways to build forms in Angular
Angular ships two form systems in the @angular/forms package:
- Template-driven forms define the form mostly in the HTML template. You add directives such as
ngModelto inputs, and Angular builds the form model behind the scenes. - Reactive forms define the form model explicitly in the component class, using
FormGroup,FormControl, andFormBuilder. The template then binds to that model.
Both systems produce the same kind of objects at runtime. Each input is represented by a FormControl, and a group of controls is represented by a FormGroup. The difference is who creates them. In a template-driven form, directives create them for you. In a reactive form, you create them yourself.
This chapter focuses on the template-driven approach. The rest of this tutorial builds on the model described here.
How the template-driven model works
When you write a template-driven form, three kinds of directives do the work.
NgFormattaches automatically to every<form>element onceFormsModuleis imported. It creates a top-levelFormGroupthat represents the whole form.NgModelattaches to any element that has anngModelattribute. It creates aFormControlfor that element and registers it with the enclosingNgForm, using the element'snameattribute as the key.- Validator directives, such as
RequiredValidatorandMinLengthValidator, attach when Angular sees attributes likerequiredandminlengthon an element that also hasngModel. They add validation rules to the control.
You never write new FormControl(). The directives do it for you, and you reach the resulting objects through template reference variables such as #f="ngForm" and #name="ngModel".
The following diagram shows how the pieces connect.
Asynchronous setup
One detail surprises many developers. NgModel registers its control with the form asynchronously, in a microtask after the first change detection pass. As a result, a control does not exist in f.controls during the constructor or in the first synchronous moment of ngOnInit. If you need to read f.controls['name'] or f.value right after the view is created, wait until the view has been initialized, for example in ngAfterViewInit, and expect an empty or incomplete value at first.
The name attribute is required
Each ngModel control inside a <form> must have a name attribute. NgForm uses that name as the key in f.value. Without it, Angular throws an error that says the control must have a name, unless you set [ngModelOptions]="{ standalone: true }". A standalone control still works, but it is not registered with the parent form, so it does not affect the form's value or validity.
A complete minimal example
The following standalone component shows the whole model at work. It binds one input with [(ngModel)], validates it with required and minlength, and shows an error only after the user has interacted with the field.
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-signup',
imports: [FormsModule],
template: `
<form #f="ngForm" (ngSubmit)="onSubmit()">
<label for="name">Name</label>
<input
id="name"
name="name"
[(ngModel)]="model.name"
#name="ngModel"
required
minlength="3"
/>
@if (name.invalid && (name.dirty || name.touched)) {
<div role="alert">
@if (name.errors?.['required']) {
<p>Name is required.</p>
}
@if (name.errors?.['minlength']) {
<p>Name must be at least 3 characters.</p>
}
</div>
}
<button type="submit" [disabled]="f.invalid">Save</button>
</form>
`,
})
export class SignupComponent {
model = { name: '' };
onSubmit() {
console.log('Submitted', this.model);
}
}Read the example in four steps:
imports: [FormsModule]makes the form directives available to this component's template.#f="ngForm"gives the template a handle on theNgFormdirective. Throughfyou can readf.invalid,f.value, and other properties of the whole form.[(ngModel)]="model.name"keepsmodel.nameand the input in sync in both directions.#name="ngModel"gives a handle on that one control.(ngSubmit)fires when the form is submitted. The button is disabled whilef.invalidis true.
Where the data lives
A template-driven form has two copies of the data, and it helps to keep them straight.
- The form model is the tree of
FormGroupandFormControlobjects that Angular creates. It holds the current value plus state such as validity. - The data model is your own object, such as
modelabove. It is a plain TypeScript object.
With [(ngModel)], Angular keeps the two in sync. When the user types, the control updates and then writes to model.name. When your code changes model.name, the control updates and then the input shows the new value. The sync is asynchronous in the other direction, because NgModel pushes model changes into the control in a microtask. That is another reason not to read control values synchronously right after you assign a property.
You can also use ngModel without a data model on the left side. Writing ngModel with no binding, or [ngModel]="value" with one-way binding, registers the control and lets you read f.value on submit, without writing back to your object on every keystroke.
Template-driven versus reactive forms
The two systems have the same capabilities in principle. They differ in where the logic sits and how easy it is to test and scale.
| Concern | Template-driven | Reactive |
|---|---|---|
| Where the form model is defined | Implicitly, by directives in the template | Explicitly, in the component class |
| Setup effort for a simple form | Low | Moderate |
| Data flow | Two-way with `ngModel`, asynchronous | Mostly synchronous and explicit |
| Dynamic fields (add or remove at runtime) | Awkward | Natural, using `FormArray` |
| Validation | Directives and attributes | Functions passed to controls |
| Unit testing | Needs rendering and waiting for change detection | Can test the model without a template |
| Reading the form model in the class | Via `@ViewChild` | Direct property access |
| Typing | Loose | Strongly typed forms |
When template-driven forms are a good fit
Choose template-driven forms when:
- The form is small and mostly static, such as a login, a signup, a contact form, or a search box.
- Validation rules map onto standard HTML attributes, with perhaps one or two custom validator directives.
- You want the quickest path from markup to a working form, and the form logic does not need to be reused outside the template.
- The team already thinks in terms of HTML attributes and simple two-way binding.
When to prefer reactive forms
Choose reactive forms when:
- Fields are added, removed, or reordered at runtime, such as a list of phone numbers or line items.
- Validation depends on several fields or on application state, and you want it in testable functions.
- You need to react to value changes as streams, for example with
valueChanges, to debounce, combine, or trigger side effects. - The form is large or long-lived, and you want the model visible and typed in the class.
- You want to unit test the form logic without rendering a template.
Mixing the two
Do not mix the systems on the same control. Using formControlName and ngModel together on one input is not supported and logs a warning in current Angular versions. An application can use template-driven forms in one component and reactive forms in another. Pick one approach per form.
Common errors at this stage
These problems come up often when someone first sets up a template-driven form.
Can't bind to 'ngModel' since it isn't a known property of 'input'. The component does not importFormsModule. Add it to theimportsarray of a standalone component, or to the NgModule that declares the component.If ngModel is used within a form tag, either the name attribute must be set or the form control must be defined as 'standalone'. Add anameattribute to the input.#f="ngForm"isundefinedor the reference fails to resolve.FormsModuleis not imported, so noNgFormdirective exists to export under that name. Importing it fixes both the error and the reference.- The form submits and the page reloads. This happens when the
<form>is not handled byNgForm, for example whenFormsModuleis missing. WithFormsModuleimported, Angular intercepts the native submit event and firesngSubmitinstead. f.valueis empty immediately after the view loads. Controls register asynchronously, as described above. Read the value later, for example inngAfterViewInitor inside the submit handler.ExpressionChangedAfterItHasBeenCheckedafter reading form state. A binding such as{{ f.valid }}can change between the check pass and the verification pass during first render, because controls register after the first pass. This tends to occur when other bindings depend on the state. Avoid driving structural changes from form state on the first render, or move that logic to a later lifecycle point.
Summary of the working model
FormsModulesupplies the directives. Import it where you use them.NgFormrepresents the whole form,NgModelrepresents one field, and validator directives add rules.- The directives build a
FormGroupandFormControlobjects for you, and the registration happens asynchronously. - Every
ngModelinside a form needs aname. - The approach suits small, static forms. Dynamic, large, or heavily tested forms usually fit reactive forms better.
Exercise
A teammate adds <input [(ngModel)]="model.email" required /> inside a <form> in a standalone component. The component fails with an error about the control's name, and a second error says ngModel is not a known property. List the two fixes, and explain why the form's f.value would still not contain the email if only one of them were applied.
Show answer
First, add FormsModule to the component's imports array so the NgModel and NgForm directives exist. Second, add a name attribute, such as name="email", to the input (or mark the control standalone with [ngModelOptions]="{ standalone: true }"). With only the name fix, Angular does not recognize ngModel at all, so no control is created. With only the FormsModule fix, the control exists but cannot register with the form without a name, so Angular throws an error. A standalone control would work but would not appear in f.value, because it is not registered with the parent form.
Exercise
You are building a form where the user can add any number of "skills" rows, each with a name and a level, and the form must be validated by a rule that compares values across all rows. Should you choose template-driven or reactive forms? Give two reasons.
Show answer
Choose reactive forms. First, the number of rows changes at runtime, and FormArray models that directly, while template-driven forms handle dynamic fields awkwardly. Second, a rule that spans several rows is easier to write as a function on the form model and to unit test without rendering a template.