使用ngModel的Angular 2双向绑定不起作用 [英] Angular 2 two way binding using ngModel is not working
问题描述
无法绑定到'ngModel',因为它不是input元素的已知属性,并且没有匹配的指令与相应的属性
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
注意:从'angular2 / angular2'
$中使用alpha.31
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);
推荐答案
Angular已于9月15日发布其最终版本。与Angular 1不一样,您可以使用Angular 2中的 ngModel
指令进行双向数据绑定,但您需要以 [(ngModel) )]
(框中的香蕉语法)。几乎所有的angular2核心指令都不支持 kebab-case
现在你应该使用 camelCase
。
Angular has released its final version on 15th of September. Unlike Angular 1 you can use ngModel
directive in Angular 2 for two way data binding, but you need write it in a bit different way like [(ngModel)]
(Banana in a box syntax). Almost all angular2 core directives doesn't support kebab-case
now instead you should use camelCase
.
现在
ngModel
指令属于FormsModule
这就是为什么你应该从导入
FormsModule
从@ angular / forms
$ in $ code> import 元数据选项AppModule
(NgModule)。此后,您可以在页面上使用ngModel
指令。
Now
ngModel
directive belongs toFormsModule
, that's why you shouldimport
theFormsModule
from@angular/forms
module insideimports
metadata option ofAppModule
(NgModule). Thereafter you can usengModel
directive inside on your page.
来自@ angular / core的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 / app.module.ts 从@ angular / core导入{NgModule};
app/app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
imports: [ BrowserModule, FormsModule ], //< added FormsModule here
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
app / main.ts
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';
const platform = platformBrowserDynamic();
platform.bootstrapModule(AppModule);
这篇关于使用ngModel的Angular 2双向绑定不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!