ChatGPT解决这个技术问题 Extra ChatGPT

Can't bind to 'ngModel' since it isn't a known property of 'input'

I have this simple input in my component which uses [(ngModel)] :

<input type="text" [(ngModel)]="test" placeholder="foo" />

And I get the following error when I launch my app, even if the component is not displayed.

zone.js:461 Unhandled Promise rejection: Template parse errors: Can't bind to 'ngModel' since it isn't a known property of 'input'.

Here is the component.ts:

import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { Intervention } from '../../model/intervention';

@Component({
   selector: 'intervention-details',
   templateUrl: 'app/intervention/details/intervention.details.html',
   styleUrls: ['app/intervention/details/intervention.details.css']
})
    
export class InterventionDetails
{
   @Input() intervention: Intervention;
    
   public test : string = "toto";
}
What is Hero plucker?
I'm having the same problem since they updated to rc5 yesterday (interestingly it works for my colleague..) I think @abreneliere is talking about their tutorials - angular.io/docs/ts/latest/tutorial
@DanielShillcock, Tour of Heroes plunker.
Yes I referred to the Tour of heroes tutorial because it does use a ngModel.
I'm just staring Angular and saw this error when doing the Tour of Heroes tutorial. Sure enough, they now call this out in the very next line and tell you how/why to correct it.

P
Peter Mortensen

Yes, that's it. In the app.module.ts file, I just added:

import { FormsModule } from '@angular/forms';

[...]

@NgModule({
  imports: [
    [...]
    FormsModule
  ],
  [...]
})

Actually, I prefer this Answer to Gabriele's (which is just a link). Here, the exact code is presented. Annoyingly, I hit this problem just following John Paps's "Introduction to Angular 2" on PluralSight, and this issue wasn't even mentioned. For them, the 2-way binding just worked.
This worked, but only after I imported it into my sub-module. It's not completely clear to beginners that this doesn't get inherited by sub-modules.
In my case, My use of braces were wrong. I was using [{ngModel}] instead of the correct one: [(ngModel)]
For those who find this because of a similar failure with Jasmine, you'll need to add these imports to the component.spec.ts file as well.
And for where to put it (regarding the Jasmine error): stackoverflow.com/questions/39584534/…
P
Peter Mortensen

In order to be able to use two-way data binding for form inputs you need to import the FormsModule package in your Angular module.

For more information, see the Angular 2 official tutorial here and the official documentation for forms.


I have to admit that I start with Angular on Monday (so 4 days ago) and was doing their tutorials so I'm pretty sure I did something wrong but for me importing FormsModule didn't work. Then I added import { FORM_DIRECTIVES } from '@angular/forms'; and added the FORM_DIRECTIVES to directives and yeah my binding is working again (to be clear it was working before rc5 release)
Which seems to be related to this stackoverflow.com/questions/31623879/…
@PetLahev the issue you're having with the tutorial is that on August 7th, when you started, the tutorials were running Release Candidate 4. As of August 8th, they are at Release Candidate 5, which has different syntax
FORM_DIRECTIVES are dead just in case
It's worth nothing that, if you are using a SharedModule, you might need to import FormsModule there aswell.
P
Peter Mortensen

For using [(ngModel)] in Angular 2, 4 & 5+, you need to import FormsModule from Angular form...

Also, it is in this path under forms in the Angular repository on GitHub:

angular / packages / forms / src / directives / ng_model.ts

Probably this is not a very pleasurable for the AngularJS developers as you could use ng-model everywhere anytime before, but as Angular tries to separate modules to use whatever you'd like you to want to use at the time, ngModel is in FormsModule now.

Also, if you are using ReactiveFormsModule it needs to import it too.

So simply look for app.module.ts and make sure you have FormsModule imported in...

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';  // <<<< import it here
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule, FormsModule // <<<< And here
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

Also, these are the current starting comments for Angular4 ngModel in FormsModule:

/**
 * `ngModel` forces an additional change detection run when its inputs change:
 * E.g.:
 * ```
 * <div>{{myModel.valid}}</div>
 * <input [(ngModel)]="myValue" #myModel="ngModel">
 * ```
 * I.e. `ngModel` can export itself on the element and then be used in the template.
 * Normally, this would result in expressions before the `input` that use the exported directive
 * to have and old value as they have been
 * dirty checked before. As this is a very common case for `ngModel`, we added this second change
 * detection run.
 *
 * Notes:
 * - this is just one extra run no matter how many `ngModel` have been changed.
 * - this is a general problem when using `exportAs` for directives!
 */

If you'd like to use your input, not in a form, you can use it with ngModelOptions and make standalone true...

[ngModelOptions]="{standalone: true}"

For more information, look at ng_model in the Angular section here.


P
Peter Mortensen

You need to import the FormsModule.

Open app.module.ts and add the lines

import { FormsModule } from '@angular/forms';

and

@NgModule({
    imports: [
       FormsModule
    ],
})

A
Anand Raja

ngModel is the part of FormsModule. And it should be imported from @angular/forms to work with ngModel.

Please change the app.module.ts as follow:

import { FormsModule } from '@angular/forms';

[...]

@NgModule({
  imports: [
    [...]
    FormsModule
  ],
  [...]
})

Thanks Anand. I ran into this during unit testing and had to add formsmodule into the spec file.
P
Peter Mortensen

Assuming you have created a new NgModule, say AuthModule dedicated to handling your authentication needs, make sure to import FormsModule in that AuthModule too.

If you'll be using the FormsModule only in the AuthModule then you wouldn't need to import the FormModule in the default AppModule.

So something like this in the AuthModule:

import { NgModule }      from '@angular/core';
import { FormsModule } from '@angular/forms';

import { authRouting } from './auth.routing';
import { LoginComponent, SignupComponent } from './auth.component';

@NgModule({
  imports:      [
    authRouting,
    FormsModule
   ],
  declarations: [
    SignupComponent,
    LoginComponent
  ]
})
export class AuthModule { }

Then forget about importing in AppModule if you don't use the FormsModule anywhere else.


I needed it at sub-module where I was using the Form features. Higher up the hierarchy was not sufficient.
T
Tharindu Lakshan

You need to import the FormsModule.

Open app.module.ts and add the lines

import { FormsModule } from '@angular/forms';

and

@NgModule({
    imports: [
       FormsModule
    ],
})

https://i.stack.imgur.com/rDaXp.png


100% requires the FormsModule to be imported. Fixed the Issue for me.
P
Peter Mortensen

Simple solution: In file app.module.ts -

Example 1

import {FormsModule} from "@angular/forms";
// Add in imports

imports: [
 BrowserModule,
 FormsModule
 ],

Example 2

If you want to use [(ngModel)] then you have to import FormsModule in app.module.ts:

import { FormsModule  } from "@angular/forms";
@NgModule({
  declarations: [
    AppComponent, videoComponent, tagDirective,
  ],
  imports: [
    BrowserModule,  FormsModule

  ],
  providers: [ApiServices],
  bootstrap: [AppComponent]
})
export class AppModule { }

Where exactly is the difference in the two examples?
in my case, had to import FormsModule on my component.module.ts
A
Arul

Import the FormsModule in those modules where you want to use the [(ngModel)]

https://i.stack.imgur.com/Ulpi6.png


P
Peter Mortensen

There are two steps you need to follow to get rid of this error:

import FormsModule in your app module Pass it as value of imports in @NgModule decorator

Basically, file app.module.ts should look like below:

    import { NgModule }      from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { FormsModule }   from '@angular/forms';
    import { AppComponent }  from './app.component';
    import {AppChildComponent} from './appchild.component';
    @NgModule({
      imports:      [ BrowserModule,FormsModule ],
      declarations: [ AppComponent, AppChildComponent ],
      bootstrap:    [ AppComponent ]
    })
    export class AppModule { }

Thank you! I'd not declared it in the imports section and it was driving me insane when I moved a component into a sub-module.
G
Ganesh

Sometimes, even though we are already imported BrowserModule, FormsModule and other related modules, we still may get the same error.

Then I realized that we need to import them in order, which is missed in my case. So the order should be like BrowserModule, FormsModule, and ReactiveFormsModule.

As per my understanding, feature modules should follow the basic modules of Angular.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule
  ],
  providers: [],
  declarations: [
    AppComponent
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

You have ReactiveFormsModule in your imports array, but not in your imports. just saying.
Is there a way to find out the order? i.e. If we have a few more modules to import, how do I confirm the sequence?
As per my understanding, Feature Modules should follow the Basic Modules of Angular. In case of Feature Modules sequence, we don't need to worry because our Error cause is not related to them.
2021 reporting in, to mention that FormsModule must be imported after NgModule. This error will appear otherwise. This answer is the only one that mentions the importance of the order!
You don't need ReactiveFormsModule when using template driven forms :-> Order irrelevant.
P
Peter Mortensen

I am using Angular 7.

I have to import ReactiveFormsModule, because I am using the FormBuilder class to create a reactive form.

import {
  FormsModule,
  ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule
  ], declarations: []})

W
WapShivam

You need to import FormsModule in your root module if this component is in the root i.e. app.module.ts

Kindly open app.module.ts

Import FormsModule from @angular/forms

Ex:

import { FormsModule } from '@angular/forms';

and

@NgModule({
imports: [
   FormsModule
],
})

A slight extension to PRao's answer.
P
Peter Mortensen

Import FormsModule in you app module.

It would let your application run well.

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {ContactListCopmponent} from './contacts/contact-list.component';
import { FormsModule }   from '@angular/forms';

import { AppComponent }  from './app.component';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule
  ],
  declarations: [
    AppComponent,ContactListCopmponent
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

P
Peter Mortensen

If you need to use [(ngModel)] first, you need to import FormsModule in app.module.ts and then add in a list of imports. Something like this:

File app.module.ts

import import {FormsModule} from "@angular/forms"; add in imports imports: [ BrowserModule, FormsModule ],

File app.component.ts

Example: and then

your name is: {{name}}


P
Peter Mortensen

I'm using Angular 5.

In my case, I needed to import ReactiveFormsModule too.

File app.module.ts (or anymodule.module.ts):

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule
  ],

ReactiveFormsModule is required when you need FormGroup, FormControl ,Validators etc. For using ngModel, you don't require ReactiveFormsModule.
@AmitChigadani Adding ReactiveFormModule is the only thing that made the error go away in my case. I'm using Angular 7.
Looks like the latest versions of Angular requires the ReactiveFormsModule to be imported for the ngModel to work. I was trained on Angular 7 and the same when I practiced it did not work, because I had the latest @angular/cli in my machine. After adding this ReactiveFormsModule, it worked perfectly.
S
Subham Pasari

If someone is still getting errors after applying the accepted solution, it could be possibly because you have a separate module file for the component in which you want to use the ngModel property in input tag. In that case, apply the accepted solution in the component's module.ts file as well.


P
Peter Mortensen

I know this question is about Angular 2, but I am on Angular 4 and none of these answers helped.

In Angular 4 the syntax needs to be

[(ngModel)]

P
Peter Mortensen

If you are still getting the error after importing FormsModule correctly then check in your terminal or (windows console) because your project is not compiling (because of another error that could be anything) and your solution has not been reflected in your browser!

In my case, my console had the following unrelated error:

Property 'retrieveGithubUser' does not exist on type 'ApiService'.


What is the action to be taken (after checking)? Please respond by editing your question, not here in comments (without "Edit:", "Update:", or similar).
Peter, you don't seem to comprehend my answer. When I say "could be anything" means that after checking the error, the universe of actions to be taken are unlimited. My answer has been upvoted 17 times, which means that many developers found my answer complete and there is no need for an edit.
P
Peter Mortensen

Import FormModule in file app.module

import { FormsModule } from '@angular/forms'; [...] @NgModule({ imports: [ [...] FormsModule ], [...] })

M
Malindu Sandaruwan

In the module you are willing to use ngModel you have to import FormsModule

import { FormsModule } from '@angular/forms';

@NgModule({
  imports: [
    FormsModule,
  ],

})
export class AbcModule { }

I was missing this in my app.module.ts, thank you Malindu!
t
thevinaychoudhary

In ngModule you need to import FormsModule, because ngModel is coming from FormsModule. Please modify your app.module.ts like the below code I have shared

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
    declarations: [
         AppComponent,
         HomeComponent
    ],
    imports: [
         BrowserModule,
         AppRoutingModule,
         FormsModule
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

P
Peter Mortensen

ngModel is coming from FormsModule. There are some cases when you can receive this kind of error:

You didn't import the FormsModule into the import array of modules where your component is declared - the component in which the ngModel is used. You have import the FormsModule into one module which is inherited of another module. In this case you have two options:

let the FormsModule be imported into the import array from both modules:module1 and module2. As the rule: Importing a module does not provide access to its imported modules. (Imports are not inherited)

declare the FormsModule into the import and export arrays in module1 to be able to see it in model2 also

(In some version I faced this problem) You have imported the FormsModule correctly, but the problem is on the input HTML tag. You must add the name tag attribute for the input, and the object bound name in [(ngModel)] must be the same as the name into the name attribute


b
blueelite

You need to import the FormsModule in app.module.ts and add the lines

 import { FormsModule } from '@angular/forms';
    @NgModule({
      imports: [
       
        FormsModule
      ]
    })

The ngModel directive declared in the FormsModule lets you bind controls in your template-driven form to properties in your data model. When you include the directive using the syntax for two-way data binding, [(ngModel)], Angular can track the value and user interaction of the control and keep the view synced with the model.


C
Chris

ngModel should be imported from @angular/forms because it is the part of FormsModule. So I advice you to change your app.module.ts in something like this:

import { FormsModule } from '@angular/forms';

[...]

@NgModule({
  imports: [
    [...]
    FormsModule
  ],
  [...]
})

How is this different from previous answers?
M
Mina Matta

For my scenario, I had to import both [CommonModule] and [FormsModule] to my module

import { NgModule } from '@angular/core' 
import { CommonModule } from '@angular/common'; 
import { FormsModule } from '@angular/forms'; 

import { MyComponent } from './mycomponent'

@NgModule({
    imports: [
        CommonModule,
        FormsModule
    ],
    declarations: [
        MyComponent 
    ]
 }) 
export class MyModule { }

N
Naeem Bashir

You need to import the FormsModule.

#Open app.module.ts
#add the lines

import { FormsModule } from '@angular/forms';
and

@NgModule({
    imports: [
       FormsModule   <--------add this 
    ],
})


if you are using reactive form then also added  ReactiveFormsModule

Unfortunately, this answer doesn't add much value to the chosen one.
@FrancescoColamonici or the other 17 answers with the exact same solution.
M
Massimiliano Kraus
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule     
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

An explanation would be in order.
G
Guntram

Sometimes you get this error when you try to use a component from a module, which is not shared, in a different module.

For example, you have 2 modules with module1.componentA.component.ts and module2.componentC.component.ts and you try to use the selector from module1.componentA.component.ts in a template inside module2 (e.g. <module1-componentA [someInputVariableInModule1]="variableFromHTTPRequestInModule2">), it will throw the error that the someInputVariableInModule1 is not available inside module1.componentA.component.ts - even though you have the @Input() someInputVariableInModule1 in the module1.componentA.

If this happens, you want to share the module1.componentA to be accessible in other modules. So if you share the module1.componentA inside a sharedModule, the module1.componentA will be usable inside other modules (outside from module1), and every module importing the sharedModule will be able to access the selector in their templates injecting the @Input() declared variable.


I have this exact problem, and you say, you should share the module so you can use componentA in ComponentC. But.. How do I share the module1? Which is the sintax to "share a module"? I guessed exporting module1 and then importing it in the module2 was enough sharing, but still having this problem
So to answer myself, this is how you share a module angular-2-training-book.rangle.io/handout/modules/…
Hey sorry i didn't see your comment that fast :) Yes, this is how you can create a SharedModule and import your own modules there, which you want to use in multiple other modules. Then you import the SharedModule where you want to use the module which is imported in the shared one.
P
Peter Mortensen

This is for the folks who use plain JavaScript instead of Type Script. In addition to referencing the forms script file on top of the page like below:

<script src="node_modules/@angular/forms/bundles/forms.umd.js"></script>

You should also tell the the module loader to load the ng.forms.FormsModule. After making the changes my imports property of NgModule method looked like below:

imports: [ng.platformBrowser.BrowserModule, ng.forms.FormsModule],