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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With