yajra yajra - 4 months ago 304
TypeScript Question

Angular 2 two way binding using ng-model is not working

Can't bind to 'ngModel' since it isn't a know property of the 'input' element and there are no matching directives with a corresponding property

Note: im using alpha.31

import { Component, View, bootstrap } from 'angular2/angular2'

@Component({
selector: 'data-bind'
})
@View({
template:`
<input id="name" type="text"
[ng-model]="name"
(ng-model)="name = $event" />
{{ name }}
`
})
class DataBinding {
name: string;

constructor(){
this.name = 'Jose';
}
}

bootstrap(DataBinding);

Answer

Update per Angular RC release 2.0.4

Angular has released release candidate version recently 2.0.4 which mean the final will come soon. Unlike Angular 1 you can use ngModel directive in Angular 2 for two way binding, but you need write it in a bit different way like [(ngModel)] (Banana in a box syntax). Now for accessing ngModel, angular2 directive doesn't support kebab-case instead they use camelCase

After angular alpha.39 release you don't need to use @View annotation.

app/app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `<h1>My First Angular 2 App</h1>
    <input type="text" [(ngModel)]="myModel"/>
    {{myModel}}
  `
})
export class AppComponent { 
  myModel: any;
}

app/main.ts

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

Demo Plunkr