Angular 4:无法绑定到'ngModel'

时间:2017-07-02 20:37:34

标签: javascript angular

我刚开始学习。我的app.components.ts文件如下所示:

import { Component, NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  // title = 'app';
  name = '';
}

我的app.component.html是这样的:

  <input type="text" [(ngModel)]="name">
  <p>{{ name }}</p>

Javascript控制台正在给我以下错误:

compiler.es5.js:1689 Uncaught Error: Template parse errors:
Can't bind to 'ngModel' since it isn't a known property of 'input'. ("et="_blank" href="http://angularjs.blogspot.ca/">Angular blog</a></h2>
  </li>
  <input type="text" [ERROR ->][(ngModel)]="name">
  <p>{{ name }}</p>
</ul>
"): ng:///AppModule/AppComponent.html@18:21
    at syntaxError (http://localhost:4200/vendor.bundle.js:18052:34)
    at TemplateParser.webpackJsonp.../../../compiler/@angular/compiler.es5.js.TemplateParser.parse (http://localhost:4200/vendor.bundle.js:29164:19)
    at JitCompiler.webpackJsonp.../../../compiler/@angular/compiler.es5.js.JitCompiler._compileTemplate (http://localhost:4200/vendor.bundle.js:43209:39)
    at http://localhost:4200/vendor.bundle.js:43129:62
    at Set.forEach (native)
    at JitCompiler.webpackJsonp.../../../compiler/@angular/compiler.es5.js.JitCompiler._compileComponents (http://localhost:4200/vendor.bundle.js:43129:19)

...

This页面建议添加FormsModule,但您可以看到它无效。

2 个答案:

答案 0 :(得分:1)

您是否错过了课程AppModule

import { Component, NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

@NgModule({
  imports:   [FormsModule ],
  //...
})
export class AppModule {} // <-- do you have this part?

答案 1 :(得分:0)

ngModel需要输入名称:

<input type="text" [(ngModel)]="name" name="nome">