我的组件中有一个简单的输入,它使用[(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

其他回答

当我第一次做这个教程时,main.ts看起来与现在略有不同。它看起来非常相似,但请注意其中的差异(上面的一个是正确的)。

对的:

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';

platformBrowserDynamic().bootstrapModule(AppModule);

旧教程代码:

import { bootstrap }    from '@angular/platform-browser-dynamic';
import { AppComponent } from './app.component';
bootstrap(AppComponent);

对于我的场景,我必须将[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属性的组件。在这种情况下,也可以在组件的module.ts文件中应用接受的解决方案。

从“@angular/forms”导入{FormsModule};@Ng模块({进口:[表单模块],})

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

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