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

当前回答

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

例如,您有两个模块,分别带有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的情况下。在我的案例中,问题出现在以下代码中:

<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">

我知道这个问题是关于Angular 2的,但我是Angular 4的,这些答案都没有帮助。

在Angular 4中,语法需要

[(ngModel)]

实际上,在大多数情况下,FormsModule已经导入。所以你要做的是确保

组件已正确添加到app.module.ts文件的声明数组中。您应该验证绑定是否拼写正确。正确拼写为[(ngModel)]

当您试图对“input”元素使用“ngModel”指令时,Angular中出现了一个著名的错误,但“ngModel”指令不被识别为“input“元素的属性。解决方案是在应用程序中导入“FormsModule”,并将其包含在模块的“imports”数组中。这样地:

import { FormsModule } from '@angular/forms';
@NgModule({
imports: [
FormsModule,
// other imports
],
// other properties
})
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 { }