If you are facing this error in your Angular application, “Can’t bind to ‘ngModel’ since it isn’t a known property of ‘input’” then here we will discuss its meaning and the way to fix it.
Why this error?
You are getting this error because you are trying to use a property that is unknown to your component.
How to fix it?
Fixing this issue doesn’t require any much effort, all we need is adding the missing dependencies.
Let’s take this example to make things more clear, consider that this is the component where we will be using ngModel
:
import { Component } from '@angular/core'; @Component({ selector: 'app-party', template: '<input type="text" name="title">', styleUrls: ['./your.component.css'], }) export class YourComponent {}
Right now, your component’s template has one input field, if we try to bind that field to a class property using ngModel
, for that we will use [(ngModel)]
import { Component } from "@angular/core"; @Component({ selector: "app-party", template: '<input type="text" name="user" [(ngModel)]="userName">', styleUrls: ["./your.component.css"] }) export class YourComponent { public pageTitle = "Mr Developer"; }
This is so far what you have probably done and which got you to this error:
Can't bind to 'ngModel' since it isn't a known property of 'input'
Solution with Code
This mean that ngModel
is unknown to YourComponent
. What we need to to do here is to tell it where it can get its definition.
So, head to your app.module.ts
file and add FormsModule
at the top of the file with other imports and then in the imports array.
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { YourComponent } from './your.component'; @NgModule({ imports: [CommonModule, FormsModule], declarations: [YourComponent], }) export class YourModule {}
Once you have done these steps your error should be gone.