数据绑定 – 使用ng-model的Angular 2双向绑定不工作

前端之家收集整理的这篇文章主要介绍了数据绑定 – 使用ng-model的Angular 2双向绑定不工作前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
无法绑定到“ngModel”,因为它不是“输入”元素的已知属性,并且没有具有对应属性的匹配指令

注意:im使用alpha.31

  1. import { Component,View,bootstrap } from 'angular2/angular2'
  2.  
  3. @Component({
  4. selector: 'data-bind'
  5. })
  6. @View({
  7. template:`
  8. <input id="name" type="text"
  9. [ng-model]="name"
  10. (ng-model)="name = $event" />
  11. {{ name }}
  12. `
  13. })
  14. class DataBinding {
  15. name: string;
  16.  
  17. constructor(){
  18. this.name = 'Jose';
  19. }
  20. }
  21.  
  22. bootstrap(DataBinding);
Angular已经在9月15日发布了其最终版本。与Angular 1不同,您可以在Angular 2中使用ngModel指令进行双向数据绑定,但是您需要以[(ngModel)](Banana在框语法中)的方式编写它。几乎所有angular2核心指令不支持kebab-case现在,而应该使用camelCase。

Now ngModel directive belongs to FormsModule,that’s why you should import the FormsModule from @angular/forms module inside imports Metadata option of AppModule(NgModule). Thereafter you can use ngModel directive inside on your page.

app / app.component.ts

  1. import { Component } from '@angular/core';
  2.  
  3. @Component({
  4. selector: 'my-app',template: `<h1>My First Angular 2 App</h1>
  5. <input type="text" [(ngModel)]="myModel"/>
  6. {{myModel}}
  7. `
  8. })
  9. export class AppComponent {
  10. myModel: any;
  11. }

app / app.module.ts

  1. import { NgModule } from '@angular/core';
  2. import { BrowserModule } from '@angular/platform-browser';
  3. import { FormsModule } from '@angular/forms';
  4. import { AppComponent } from './app.component';
  5.  
  6. @NgModule({
  7. imports: [ BrowserModule,FormsModule ],//< added FormsModule here
  8. declarations: [ AppComponent ],bootstrap: [ AppComponent ]
  9. })
  10.  
  11. export class AppModule { }

app / main.ts

  1. import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
  2. import { AppModule } from './app.module';
  3.  
  4. const platform = platformBrowserDynamic();
  5. platform.bootstrapModule(AppModule);

Demo Plunkr

猜你在找的Angularjs相关文章