我使用的是Angular 4,我在控制台得到了一个错误:

不能绑定到ngModel,因为它不是input的已知属性

我该如何解决这个问题?


当前回答

如果你想对表单输入使用双向数据绑定,你需要在Angular模块中导入formsmodule包。要了解更多信息,请参阅Angular 2官方教程和表单的官方文档

在app.module.ts中添加以下行:

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

[...]

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

其他回答

你的ngModel没有工作,因为它还不是你的NgModule的一部分。

你必须告诉NgModule你有权在整个应用中使用ngModel,你可以通过在app.module.ts -> imports->[]中添加FormsModule来实现。

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

@NgModule({

   imports: [ FormsModule ],       // HERE

   declarations: [ AppComponent ],
   bootstrap: [ AppComponent ]
 })

首先导入FormsModule,然后在component.ts中使用ngModel

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

@NgModule({
 imports: [ 
            FormsModule  
          ];

HTML代码:

<input type='text' [(ngModel)] ="usertext" />

在我的情况下,我拼写错误,我是指ngmodel而不是ngmodel:)希望它有帮助!

Expected - [(ngModel)] Actual - [(ngmodel)]

在你的NgModule导入中添加FormsModule(因此ngModel是FormsModule的一部分)。

注意,它可以是AppModule,也可以是通过惰性加载加载的特性模块。

imports: [
   ...,
   FormsModule,
   ...
]

我在用Karma/Jasmine测试Angular 6应用时遇到了这个错误。我已经在顶层模块中导入了FormsModule。但是当我添加一个使用[(ngModel)]的新组件时,我的测试开始失败。在这种情况下,我需要在我的TestBed TestingModule中导入FormsModule。

beforeEach(async(() => {
  TestBed.configureTestingModule({
    imports: [
      FormsModule
    ],
    declarations: [
      RegisterComponent
    ]
  })
  .compileComponents();
}));