我的组件中有一个简单的输入,它使用[(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的情况下。在我的案例中,问题出现在以下代码中:

<input type="text" class="form-control" id="firstName"
                   formControlName="firstName" placeholder="Enter First Name"
                   value={{user.firstName}} [(ngModel)]="user.firstName">

我通过更改表单ControlName->name来修复它

<input type="text" class="form-control" id="firstName"
                   name="firstName" placeholder="Enter First Name"
                   value={{user.firstName}} [(ngModel)]="user.firstName">

其他回答

如果在正确导入FormsModule后仍然出现错误,请检查您的终端或(windows控制台),因为您的项目未在编译(因为可能是其他错误),并且您的解决方案尚未反映在浏览器中!

在我的情况下,我的控制台出现了以下不相关的错误:

类型“ApiService”上不存在属性“retrieveGithubUser”。

ngModel来自FormsModule。在某些情况下,您可能会收到此类错误:

您没有将FormsModule导入到声明组件的模块导入数组中,即使用ngModel的组件。您已经将FormsModule导入一个模块,该模块继承了另一个模块。在这种情况下,您有两个选项:

让FormsModule从两个模块(module1和module2)导入导入数组。通常:导入模块不会提供对其导入模块的访问权限。(导入不继承)将FormsModule声明到module1中的导入和导出数组中,以便能够在model2中看到它

(在某些版本中,我遇到了这个问题)您正确导入了FormsModule,但问题出在输入HTML标记上。必须为输入添加name标记属性,[(ngModel)]中的对象绑定名称必须与name属性中的名称相同

即使如上所述添加了FormsModule,我也会遇到同样的错误。因此,只需要简单的重新启动即可完成任务。

我在运行Angular测试时遇到了同样的错误,因为规范文件中没有添加FormsModule。

我们需要将其添加到所有规范文件中,而为了使应用程序成功运行,我们将在app.module.ts文件中的一个位置添加它。

假设您已经创建了一个新的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中导入。