Angular 2 使用 ngModel 的双向绑定不起作用 [英] Angular 2 two way binding using ngModel is not working

查看:29
本文介绍了Angular 2 使用 ngModel 的双向绑定不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无法绑定到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

注意:我使用的是 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,这就是为什么你应该从@importFormsModuleAppModule(NgModule) 的 imports 元数据选项中的 angular/forms 模块.此后,您可以在页面内使用 ngModel 指令.

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

演示 Plunkr

这篇关于Angular 2 使用 ngModel 的双向绑定不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆