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

当前回答

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

在Angular 4中,语法需要

[(ngModel)]

其他回答

在ngModule中,您需要导入FormsModule,因为ngModel来自FormsModule。请按照我分享的以下代码修改app.module.ts

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
    declarations: [
         AppComponent,
         HomeComponent
    ],
    imports: [
         BrowserModule,
         AppRoutingModule,
         FormsModule
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

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

在Angular 4中,语法需要

[(ngModel)]

您需要导入FormsModule。

打开app.module.ts并添加行

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

and

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

当我第一次做这个教程时,main.ts看起来与现在略有不同。它看起来非常相似,但请注意其中的差异(上面的一个是正确的)。

对的:

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';

platformBrowserDynamic().bootstrapModule(AppModule);

旧教程代码:

import { bootstrap }    from '@angular/platform-browser-dynamic';
import { AppComponent } from './app.component';
bootstrap(AppComponent);

我面临同样的问题,原因是我在MenuComponent中使用ngModel。我在app.module.ts中导入了MenuComponent,但忘记声明它。

声明MenuComponent解决了我的问题。如下图所示: