我的组件中有一个简单的输入,它使用[(ngModel)]:

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

当我启动应用程序时,即使没有显示组件,也会出现以下错误。

zone.js:461未处理的Promise拒绝:模板解析错误:无法绑定到“ngModel”,因为它不是“input”的已知属性。

以下是组件。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";
}

当前回答

ngModel来自FormsModule。在某些情况下,您可能会收到此类错误:

您没有将FormsModule导入到声明组件的模块导入数组中,即使用ngModel的组件。您已经将FormsModule导入一个模块,该模块继承了另一个模块。在这种情况下,您有两个选项:

让FormsModule从两个模块(module1和module2)导入导入数组。通常:导入模块不会提供对其导入模块的访问权限。(导入不继承)将FormsModule声明到module1中的导入和导出数组中,以便能够在model2中看到它

(在某些版本中,我遇到了这个问题)您正确导入了FormsModule,但问题出在输入HTML标记上。必须为输入添加name标记属性,[(ngModel)]中的对象绑定名称必须与name属性中的名称相同

其他回答

要消除此错误,需要遵循两个步骤:

在应用程序模块中导入FormsModule将其作为@NgModule decorator中的导入值传递

基本上,app.module.ts文件应该如下所示:

    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 { }

在应用程序模块中导入FormsModule。

这将使您的应用程序运行良好。

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 { }

最近,我发现错误不仅发生在您忘记在模块中导入FormsModule的情况下。在我的案例中,问题出现在以下代码中:

<input type="text" class="form-control" id="firstName"
                   formControlName="firstName" placeholder="Enter First Name"
                   value={{user.firstName}} [(ngModel)]="user.firstName">

我通过更改表单ControlName->name来修复它

<input type="text" class="form-control" id="firstName"
                   name="firstName" placeholder="Enter First Name"
                   value={{user.firstName}} [(ngModel)]="user.firstName">

我使用的是Angular 7。

我必须导入ReactiveFormsModule,因为我正在使用FormBuilder类创建一个反应式表单。

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

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

注意:请记住,ngModel指令被定义为Angular FormsModule的一部分,您需要在Angular模块元数据的imports:[…]部分中包含FormsModul,在该部分中使用它。