我的组件中有一个简单的输入,它使用[(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属性的组件。在这种情况下,也可以在组件的module.ts文件中应用接受的解决方案。

其他回答

对于我的场景,我必须将[CommonModule]和[FormsModule]导入到我的模块

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

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

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

有关更多信息,请参阅此处的Angular 2官方教程和表单的官方文档。

在应用程序模块中导入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已经导入。所以你要做的是确保

组件已正确添加到app.module.ts文件的声明数组中。您应该验证绑定是否拼写正确。正确拼写为[(ngModel)]