Sub topic 2
Enabling FormsModule in a component
This chapter covers how to turn on template-driven forms in a standalone Angular component. It assumes you know TypeScript classes, Angular components and templates, and basic template syntax such as property binding, event binding and template reference variables. It also assumes you know basic HTML form elements.
Why FormsModule is needed
Template-driven forms rely on directives such as ngModel, ngForm and ngModelGroup. These directives are not part of the core template language. They live in FormsModule, which is exported by the @angular/forms package.
A component only sees the directives it imports. If you skip the import, Angular does not treat <form> or ngModel specially, and your form never gets a form model.
Importing FormsModule
In a standalone component, add FormsModule to the imports array of the @Component decorator.
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" />
<button type="submit">Save</button>
</form>
`,
})
export class SignupComponent {
model = { name: '' };
onSubmit() {
console.log('Submitted', this.model);
}
}Once FormsModule is imported, two things happen in this template:
- Angular attaches an
NgFormdirective to the<form>element. It collects every control inside the form. - The
NgModeldirective on the input creates a form control and registers it with the enclosingNgForm.
The #f="ngForm" reference gives you the NgForm instance, which you will use in later chapters to read the form's validity and state.
Where to import it
Import FormsModule in each standalone component that uses template-driven directives. Imports are not inherited from a parent component. If a child component has its own form, it needs its own import.
In an application that still uses NgModules, add FormsModule to the imports array of the NgModule that declares the component.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { SignupComponent } from './signup.component';
@NgModule({
declarations: [SignupComponent],
imports: [BrowserModule, FormsModule],
})
export class AppModule {}Here SignupComponent must be a non-standalone component, since NgModules declare only those.
How the directives are matched
Angular matches directives by selector. FormsModule provides directives whose selectors match form:not([ngNoForm]):not([ngNativeValidate]) and [ngModel]:not([formControlName]):not([formControl]). That is why a plain <form> becomes an NgForm automatically once the module is imported.
You can opt out for a single form. Add ngNoForm to keep Angular from attaching NgForm, or ngNativeValidate to keep the browser's own validation bubbles.
Common errors
Two other mistakes are frequent:
- Missing
nameattribute. Inside a<form>, everyngModelcontrol needs anameattribute, becauseNgFormuses it as the control's key. Without it, Angular throws an error saying the control must have a name. You can avoid this only with[ngModelOptions]="{standalone: true}", which keeps the control out of the form. - Importing
ReactiveFormsModuleby mistake. That module serves reactive forms and does not providengModel. Both modules can be imported together, but one control should not use both approaches.
Exercise
A template contains <form #f="ngForm"><input [(ngModel)]="city" /></form>, and the component imports FormsModule. The app throws an error at runtime. What is the most likely cause, and what is the fix?
Show answer
The input has no name attribute. Inside a form, NgForm registers each ngModel control under its name, so the control must have one. Add name="city" to the input, or use [ngModelOptions]="{standalone: true}" if the control should stay outside the form.
Exercise
A child component renders its own <form> with ngModel. The parent component already imports FormsModule. Does the child work without its own import?
Show answer
No. Standalone components do not inherit imports from their parents, so the child must list FormsModule in its own imports array.