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

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

我该如何解决这个问题?


当前回答

这是一个正确答案。 你需要导入FormsModule

首先在app.module.ts中

**

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

** 在app.component.spec.ts中的第二个

import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule,
        FormsModule
      ],
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));

最好的问候,希望会有所帮助。

其他回答

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

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

@NgModule({
 imports: [ 
            FormsModule  
          ];

HTML代码:

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

如果在导入formsmodule之后问题仍然存在,请检查Input是否具有“name”属性,其值等于页面上的另一个输入。

如果双向绑定不起作用,您应该验证以下内容。

在html中ngModel应该这样调用。不依赖于输入元素的其他属性

<输入[(ngModel)] = >“inputText

确保FormsModule被导入到模块文件app.modules.ts中

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

@NgModule({
    declarations: [
        AppComponent,
        HomeComponent // suppose, this is the component in which you are trying to use two ay binding
    ],
    imports: [
        BrowserModule,
        FormsModule,
        // other modules
],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule { }

方法的声明中添加了你试图使用ngModel进行双向绑定的组件。在前面第2点中添加的代码

这就是使用ngModel使双向绑定工作所需做的所有事情,这在angular 9中都得到了验证

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

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

为了对表单输入使用双向数据绑定,你需要在Angular模块中导入FormsModule包。

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

@NgModule({
    imports: [
         FormsModule      
    ]

EDIT

因为有很多相同问题的重复问题,我正在加强这个答案。

有两个可能的原因

缺少FormsModule,因此将此添加到您的模块, import {FormsModule} from '@angular/forms'; @NgModule ({ 进口:[ FormsModule ] 检查input标签中[(ngModel)]的语法/拼写