微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

无法绑定到“ngModel”,因为它不是“输入”元素的已知属性,并且没有具有对应属性的匹配指令

注意:im使用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)](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

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

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

Demo Plunkr

原文地址:https://www.jb51.cc/angularjs/145719.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐