How to Fix Can't Bind to ngModel Angular Error
The error
Can't bind to 'ngModel' happens because Angular's FormsModule is not imported in your module. To fix it, import FormsModule from @angular/forms and add it to the imports array of your Angular module.Why This Happens
This error occurs because Angular does not recognize the ngModel directive without the FormsModule. The ngModel directive is part of Angular's forms package, and if you forget to import FormsModule in your module, Angular cannot bind the data and throws this error.
html
<input [(ngModel)]="name" placeholder="Enter your name">
Output
Error: Can't bind to 'ngModel' since it isn't a known property of 'input'.
The Fix
To fix this error, import FormsModule from @angular/forms in your Angular module and add it to the imports array. This tells Angular to recognize and use the ngModel directive.
typescript
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; @NgModule({ declarations: [AppComponent], imports: [BrowserModule, FormsModule], bootstrap: [AppComponent] }) export class AppModule { } // In your component template: // <input [(ngModel)]="name" placeholder="Enter your name">
Output
Input box binds correctly to the 'name' property without errors.
Prevention
Always remember to import FormsModule when using ngModel for two-way data binding. Use Angular CLI to generate components and modules, which often adds necessary imports automatically. Enable strict linting rules to catch missing imports early during development.
Related Errors
Other similar errors include:
- Can't bind to 'formControl' since it isn't a known property: Fix by importing
ReactiveFormsModule. - Template parse errors: 'ngModel' is not a known property: Usually fixed by importing
FormsModule.
Key Takeaways
Import FormsModule from @angular/forms to use ngModel directive.
Add FormsModule to the imports array in your Angular module.
Use Angular CLI to scaffold projects to avoid missing imports.
Enable linting to catch missing module imports early.
For reactive forms, import ReactiveFormsModule instead.