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

问题描述

无法绑定到'ngModel',因为它不是'输入'元素的专有财产,有一个相应的属性没有匹配的指令

请注意:使用alpha.31 IM

 进口{组件,查看,引导}从'angular2 / angular2@零件({
    选择:数据绑定
})
@视图({
    模板:`
        <输入ID =名称类型=文本
            [NG模型] =名
            (NG-模式)=NAME = $事件/>
        {{ 名称 }}
    `
})
类数据绑定{
    名称:字符串;    构造函数(){
        this.name ='何';
    }
}引导(数据绑定);


解决方案

每角测试版更新2.0.6

角已经发布beta版本最近角测试版 2.0.1 版本。其中有翻天覆地的变化。现在Angular2提供了 ngModel 指令为双向绑定,角1,但你需要它写在有点不同的方式,比如 [(ngModel)] 香蕉在一个盒子里的语法)。现在访问 ngModel 指令不需要加入 formDirectives angular2 /表格组件查看已被移动到 angular2 /芯模块和放大器; 引导已被移动到 angular2 /平台/浏览器模块。现在angular2指令不支持烤肉情况而是使用 cammelCase

在角alpha.39版本中,您不需要使用 @View 注释。

看看下面code。

code

 进口{}组件从angular2 /核心;
从angular2 /平台/浏览器的进口{}引导;//注释部分
@零件({
    选择:数据绑定,
    模板:'<输入[(ngModel)] =名/>< BR>我的名字{{名}}'
})
//组件控制器
出口类DataBindingComponent {
  名称:字符串;
  构造函数(){
    this.name ='潘卡';
  }
}引导(数据绑定);

较早的答案(当Angular2是alpha版本)

Below are the all directives on formDirectives module

You need to import formDirectives from angular2/forms using import {formDirectives} from 'angular2/forms'; to achieve two way binding.

Initially angular2 doesn't have an two way binding feature, now they have added ng-model sugar to achieve two way binding.

<input [(ng-model)]="name">

Here usage of square brackets ([..]) suggests the property binding and round brackets ((..)) for event binding. Basically when you use ng-model, you are enabling both the bindings ng-model is more of an event.

Internally anglular2 creates an observable event(with EventEmitter) to track the value changes in the bound element and update the bound property respectively.

Simple NgModel Directive Implementation

@Directive({
  selector: '[ng-model]',
  properties: ['ngModel'],
  events: ['ngModelChanged: ngModel'],
  host: {
    "[value]": 'ngModel',
    "(input)": "ngModelChanged.next($event.target.value)"
  }
})
class NgModelDirective {
  ngModel:any; // stored value
  ngModelChanged:EventEmitter; // an event emitter
}

Above has been found from one of the good article on Angular2

Updated Code

import { Component, View, bootstrap } from 'angular2/angular2';
import {formDirectives} from 'angular2/forms';
// Annotation section
@Component({
    selector: 'data-bind'
})@ View({
  template: '<input [ng-model]="name" (ng-model)="name=$event"></input> {{name}}',
  directives: [formDirectives]
})
// Component controller
export class DataBinding { //export is needed before class
  name: string;
  constructor() {
    this.name = 'Jose';
  }
}

bootstrap(DataBinding);

Working Plunkr

这篇关于角2双向使用NG-模型绑定不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 03:40