Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't bind to 'ngModel' since it isn't a known property of 'input' despite importing FormsModule [duplicate]

I am following the Angular 2 tutorial on MVA. I can't seem to get the two way binding to work. I applied the fix in Can't bind to 'ngModel' since it isn't a known property of 'input' but this isn't working. The error is below:

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 ;

My main.ts code is as follows:

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);

The code works if I comment out the two way binding. How can I fix this?

like image 832
topher Avatar asked Aug 19 '16 13:08

topher


1 Answers

You may use below,

 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);

Here is the Plunker!!

However you should consider using NgModule, and import the FormsModule in it.

like image 92
Madhu Ranjan Avatar answered Sep 20 '22 15:09

Madhu Ranjan