我的组件中有一个简单的输入,它使用[(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(例如,从共享模块),如果导入的组件未在声明中声明,也会发生此错误:

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

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

其他回答

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

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

确保[(ngModel)]实际拼写为“ngModel”,大写为M。我花了几分钟没看到这个

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

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

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

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

简单解决方案:在文件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 { }