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

当前回答

此错误的主要原因是您忘记在app.module.ts中导入FormsModule。

但有时在大型项目中,您可能会忘记在其模块中添加组件,并遇到此错误。

其他回答

假设您已经创建了一个新的NgModule,比如说AuthModule专门用于处理您的身份验证需求,请确保也在该AuthModule中导入FormsModule。

如果您将仅在AuthModule中使用FormsModule,则无需在默认AppModule中导入FormModule。

因此,AuthModule中的内容如下:

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

import { authRouting } from './auth.routing';
import { LoginComponent, SignupComponent } from './auth.component';

@NgModule({
  imports:      [
    authRouting,
    FormsModule
   ],
  declarations: [
    SignupComponent,
    LoginComponent
  ]
})
export class AuthModule { }

然后,如果您在其他任何地方都不使用FormsModule,请忘记在AppModule中导入。

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

简单解决方案:在文件app.module.ts中-

示例1

import {FormsModule} from "@angular/forms";
// Add in imports

imports: [
 BrowserModule,
 FormsModule
 ],

示例2

如果要使用[(ngModel)],则必须在app.module.ts中导入FormsModule:

import { FormsModule  } from "@angular/forms";
@NgModule({
  declarations: [
    AppComponent, videoComponent, tagDirective,
  ],
  imports: [
    BrowserModule,  FormsModule

  ],
  providers: [ApiServices],
  bootstrap: [AppComponent]
})
export class AppModule { }

在Angular中使用双向绑定之前,需要将FormsModule包导入到模块中。

通过将FormsModule添加到模块内的imports数组(例如app.module.ts),可以这样做。

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

@NgModule({
  imports: [
    ...,
    FormsModule     <-------
  ],
  [...]
})

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

例如,您有两个模块,分别带有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()声明变量的选择器。