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

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

问题描述

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

来自@ 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);

演示Plunkr

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

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