我的组件中有一个简单的输入,它使用[(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应该从@angular/forms导入,因为它是FormsModule的一部分。所以我建议您更改app.module.ts,如下所示:

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

[...]

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

其他回答

对于我的场景,我必须将[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 { }

确保采用模板驱动的表单方法(https://angular.io/guide/forms),正如@Nikita Sychou已经提到的,您已经用“name”属性修饰了输入字段,例如

<form>
   <input [(ngModel)]="form.email" name="email"></input>

并且FormsModule已导入关联的@NgModule中。这两者都是避免“无法绑定到ngModel”错误的前提条件。如果IDE中仍然存在样式错误,例如IntelliJ抱怨ngModel指令,请忽略它们。。你很好去:-)

我从RC1升级到RC5并收到此错误。

我完成了迁移(引入了一个新的app.module.ts文件,将package.json更改为包含新版本和缺失的模块,最后根据Angular2快速启动示例将main.ts更改为相应的引导)。

我做了一次npm更新,然后做了一个npm过时,以确认安装的版本是正确的,但仍然没有运气。

我最终彻底删除了node_modules文件夹,并重新安装了npm install-瞧!问题已解决。

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

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

即使在功能模块中直接或间接导入FormsModule(例如,从共享模块),如果导入的组件未在声明中声明,也会发生此错误:

我参加了Deborah Kurata的Angular Routing课程。当我在Angular Route的组件属性上添加导入的组件ProductEditInfoComponent时,我忘记在声明属性上添加ProductEditInfoComponent。

在声明属性上添加ProductEditInfoComponent将解决NG8002:无法绑定到“ngModel”,因为它不是“input”的已知属性。问题: