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

当前回答

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

在应用程序模块中导入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 { }

其他回答

对于Angular 2的任何版本,您都需要在app.module.ts文件中导入FormsModule,它将解决此问题。

在ngModule中,您需要导入FormsModule,因为ngModel来自FormsModule。请按照我分享的以下代码修改app.module.ts

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

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

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule     
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

有时,当您尝试在不同的模块中使用未共享的模块中的组件时,会出现此错误。

例如,您有两个模块,分别带有module.componentA.component.ts和module.componentC.component.ts,您尝试使用module2内模板中module.componentA.component.ts中的选择器(例如<module1 componentA[someInputVariableInModule1]=“variableFromHTTPRequestInModule2”>),它将抛出错误:someInputVariableInModule1在module.componentA.component.ts中不可用-即使您在module.componentA中有@Input()someInputVariable InModule1。

如果发生这种情况,您希望共享module.componentA,以便在其他模块中访问。因此,如果在sharedModule内共享module1.componentA,则module1.companentA将在其他模块内(在module1之外)可用,并且导入sharedModules的每个模块都可以访问其模板中注入@Input()声明变量的选择器。

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

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