Sub topic 2
Enabling FormsModule in a component
This chapter assumes you know TypeScript classes, Angular components and templates, and basic template syntax (property binding, event binding, template reference variables). It also assumes you have used standalone components. Here you will learn what FormsModule provides, how to import it in standalone and NgModule-based code, and how to recognize the errors you get when it is missing.
What FormsModule gives you
Template-driven forms are built from directives, which are classes that Angular attaches to elements in a template. A plain <input> or <form> has no form behavior of its own. The directives that add it ship in @angular/forms, and FormsModule bundles them.
The ones you will use most:
| Directive | Selector (simplified) | Purpose |
|---|---|---|
| `NgModel` | `[ngModel]` | Creates a form control for an element and binds it to data |
| `NgForm` | `form`, `ng-form`, `[ngForm]` | Creates a form-level group that collects every `ngModel` inside it |
| `NgModelGroup` | `[ngModelGroup]` | Nests several controls under one key |
| `NgNoValidate` | `form` | Adds `novalidate` so the browser's own validation bubbles do not compete with Angular's |
| Validator directives | `[required]`, `[minlength]`, `[pattern]`, `[email]` and others | Turn HTML validation attributes into Angular validators |
| Value accessors | `input`, `select`, `textarea`, checkbox, radio and others | Connect each kind of DOM element to a control |
Two details in this table matter in practice.
First, NgForm matches any <form> element automatically. You do not write ngForm on the tag to get a form model. You write #f="ngForm" only when you want a reference to the directive instance (covered in a later chapter).
Second, the validator directives match on attributes such as required, but only when the element also has ngModel (or another form directive). That is why a bare <input required> outside a form setup does nothing in Angular.
How the import activates directives
Angular decides which directives apply to an element when it compiles a component's template. It looks only at the directives and modules that component declares in scope. If FormsModule is not in scope, ngModel is just an unknown attribute.
Standalone components
In current Angular, components are standalone by default. A standalone component lists the things its template needs in its own imports array.
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-nickname',
imports: [FormsModule],
template: `
<label for="nick">Nickname</label>
<input id="nick" name="nick" [(ngModel)]="nickname" />
<p>Hello, {{ nickname || 'stranger' }}</p>
`,
})
export class NicknameComponent {
nickname = '';
}This is a complete component. Typing in the input updates nickname, and changing nickname in code updates the input. The [(ngModel)] syntax is covered in the next chapter, so for now treat it as "two-way binding".
To run it, render it from a bootstrapped root component:
import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { NicknameComponent } from './nickname.component';
@Component({
selector: 'app-root',
imports: [NicknameComponent],
template: `<app-nickname />`,
})
class AppComponent {}
bootstrapApplication(AppComponent);Notice that AppComponent does not need FormsModule. It only uses app-nickname, and NicknameComponent carries its own imports.
Imports are not inherited
A standalone component's imports apply only to its own template. If a parent imports FormsModule and a child component uses ngModel, the child must import it too. The same holds in the other direction: importing FormsModule in a child does not make it available in the parent.
If several components in your project need the same set of form imports, export them as a constant array:
import { FormsModule } from '@angular/forms';
import { NgClass } from '@angular/common';
export const FORM_IMPORTS = [FormsModule, NgClass] as const;A component then writes imports: [...FORM_IMPORTS]. Use this only when it removes real repetition. A plain imports: [FormsModule] is easier to read.
NgModule-based components
Older code declares components in an NgModule. There, FormsModule goes in the module's imports, and it applies to every component declared in that module.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { SignupComponent } from './signup.component';
@NgModule({
declarations: [AppComponent, SignupComponent],
imports: [BrowserModule, FormsModule],
bootstrap: [AppComponent],
})
export class AppModule {}For a feature module, import FormsModule in that feature module. A module's imports do not leak into other modules, so the root module's FormsModule does not help a lazy-loaded feature module.
FormsModule or ReactiveFormsModule
Angular has two form modules because it has two form styles.
FormsModulesupports template-driven forms:ngModel,ngForm,ngModelGroup.ReactiveFormsModulesupports reactive forms:formGroup,formControl,formControlName.
They are separate on purpose. You can import both in one component, but you should not mix the two styles on the same <form>. Putting [formGroup] on a form switches off the automatic NgForm for that element, because NgForm's selector excludes elements with formGroup. Pick one style per form.
Errors you will see when the import is missing
Most mistakes around this topic show up the first time you run the app. Learn to match the message to the cause.
Unknown property ngModel
Can't bind to 'ngModel' since it isn't a known property of 'input'.The error code is NG8002 at compile time, or NG0303 at runtime in some setups. The cause is that FormsModule is not in scope for this component. Check the imports array of the component whose template uses ngModel, not its parent's.
Missing name attribute inside a form
If ngModel is used within a form tag, either the name attribute must be set
or the form control must be defined as 'standalone' in ngModelOptions.This one appears only when FormsModule is working. Inside a <form>, each ngModel registers itself with the form under its name. Without a name, Angular cannot pick a key. Fix it by adding name="...". The standalone option is for a control that should not join the form, and a later chapter covers it.
No value accessor
No value accessor for form control with name: 'x'A value accessor is the adapter between a DOM element and a control. FormsModule provides accessors for native inputs, selects, checkboxes and radios. This error means you put ngModel on something that has none, usually a custom component. Either put ngModel on a native element inside it, or make the component implement ControlValueAccessor.
Form validation seems to do nothing
If you add required to an input and the control never becomes invalid, check these in order:
- The element has
ngModel. FormsModuleis imported in this component.- Under
<form>, the element has aname.
Without ngModel, the required attribute is only plain HTML, and the browser handles it. The novalidate attribute that FormsModule adds to <form> also stops the browser's own validation from blocking submission, so a missing import can change behavior in two ways at once.
Testing: import it there too
A test host does not inherit your application's imports. When you test a component that uses ngModel, the component's own imports still apply, because it is standalone. With NgModule-declared components, add FormsModule to the test module:
import { TestBed } from '@angular/core/testing';
import { FormsModule } from '@angular/forms';
import { SignupComponent } from './signup.component';
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [FormsModule],
declarations: [SignupComponent],
}).compileComponents();
});If SignupComponent is standalone, replace declarations: [SignupComponent] with SignupComponent inside imports. A later chapter covers testing in full.
Checklist
- Import
FormsModulefrom@angular/forms. - Add it to the
importsof the standalone component (or the NgModule) whose template usesngModel. - Give every
ngModelinside a<form>aname. - Do not combine
[formGroup]withngModelon the same form.
Exercise
A parent standalone component imports FormsModule. Its template includes <app-profile-editor />, a standalone child with an <input [(ngModel)]="bio" name="bio" />, but the child's imports array is empty. What error do you get, and what is the fix?
Show answer
Angular reports that it can't bind to 'ngModel' since it isn't a known property of 'input' (NG8002), because imports apply only to the component that lists them. The fix is to add FormsModule to the imports array of the child component, ProfileEditorComponent. The parent's import does not need to change unless the parent's own template also uses ngModel.
Exercise
Inside a <form>, you write <input [(ngModel)]="email" required /> and see an error about the name attribute. Give two valid ways to resolve it, and say how they differ.
Show answer
Add name="email". The control then registers with the form under the key "email", and it contributes to the form's value and validity. Alternatively, use [ngModelOptions]="{ standalone: true }". The control still binds to email, but it is not registered with the parent form, so it does not appear in the form's value or affect the form's validity.