无法绑定到'ngModel',因为尽管导入了FormsModule,它仍然不是'input'的已知属性

时间:2016-08-19 13:14:03

标签: angular angular2-forms

我关注Angular 2 tutorial on MVA。我似乎无法让双向绑定工作。我在Can't bind to 'ngModel' since it isn't a known property of 'input'中应用了此修复程序,但这不起作用。错误如下:

Unhandled Promise rejection: Template parse errors:
Can't bind to 'ngModel' since it isn't a known property of 'input'. ("
        <p>
            <input [ERROR ->][(ngModel)]="sampleText" ><br/>
            <span>{{sampleText}}</span>
        </p>
"): TasksComponent@2:19 ; Zone: <root> ; Task: Promise.then ;

我的main.ts代码如下:

import { bootstrap } from '@angular/platform-browser-dynamic';
import { Component, OnInit } from '@angular/core';

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


@Component({
    selector: 'tasks',
    template: `
        <p>
            <input [(ngModel)]="sampleText" ><br/>
            <span>{{sampleText}}</span>
        </p>
    `
})
export class TasksComponent implements OnInit {
    sampleText: string = "";
    ngOnInit() {}
}

@Component({
    selector: 'app',
    directives: [TasksComponent],
    template: `
        <h1>Hello World</h1>
        <tasks></tasks>
    `
})
export class AppComponent implements OnInit {
    constructor() {}

    ngOnInit() {}
}

bootstrap(AppComponent);

如果我注释掉双向绑定,代码就可以工作。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:5)

您可以在下面使用,

 import { bootstrap } from '@angular/platform-browser-dynamic';
 import { Component, OnInit } from '@angular/core';

 // Import and use below directive
 import { FORM_DIRECTIVES } from '@angular/forms'; 


 @Component({
    selector: 'tasks',
    template: `
     <p>
        <input [(ngModel)]="sampleText" ><br/>
        <span>{{sampleText}}</span>
     </p>
   `
   , directives: [FORM_DIRECTIVES]
 })
 export class TasksComponent implements OnInit {
   sampleText: string = "";

   constructor() {}

   ngOnInit() {}
 }

 @Component({
   selector: 'my-app',
   directives: [TasksComponent],
   template: `
      <h1>Hello World</h1>
      <tasks></tasks>
    `
 })
export class AppComponent implements OnInit {
   constructor() {}

   ngOnInit() {}
}

bootstrap(AppComponent);

以下是Plunker!!

但是,您应该考虑使用NgModule,然后在其中导入FormsModule

希望这有帮助!