2015-08-30 71 views
2

我正在構建一個關於Angular 2遷移演示的演示應用程序。我的部分應用程序有<input ng-model="" />,我想將其更改爲「Angular 2的方式」。 所以,我有兩個選擇:Angular 2.0和ng-model

  1. 使用「formDirectives」,這是我的演示矯枉過正,因爲我沒有一個形式在這裏,只有一些投入更新的一些數據
  2. 使用什麼維克多Savkin (表格2角隊)在他的(大)表明post

<input ([ng-model])="todo.text" />

ng-model是一個指令:

import {Directive, EventEmitter} from 'angular2/angular2'; 

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

我實現了這個在我的演示項目是這樣的:

import {Component, View} from 'angular2/angular2'; 
import {NgModelDirective as NgModel} from '../ng-model/ng-model'; 

@Component({ 
    selector: 'font-size-component', 
    properties: [ 
    'font' 
    ] 
}) 
@View({ 
    template: `<input id="fontSize" class="form-control" name="fontSize" ([ng-model])="font.fontSize"/>`, 
    directives: [ 
    NgModel 
    ] 
}) 

export class FontSizeComponent { 
    constructor() { 
    } 
} 

我的輸入是越來越與所提供的數據呈現(屬性結合[NG-模型工作],但該事件結合不工作,給了以下錯誤:

EXCEPTION: TypeError: Cannot read property 'observer' of undefined

EXCEPTION: TypeError: Cannot read property 'location' of undefined

EXCEPTION: TypeError: Cannot read property 'hostView' of undefined

當我刪除了這條線從events: ['ngModelChanged: ngModel'],指令ng-model所有錯誤消失......

我非常新的2角(大家都可能是),並嘗試瞭解我在做什麼錯在這裏。 ..

編輯

OK,所以reading後多一點我確信,使用formDirectives不是這樣的矯枉過正。我的解決方案(採用了棱角分明2 阿爾法35是現在FORM_DIRECTIVES代替formDirectives):

import {Component, View, FORM_DIRECTIVES} from 'angular2/angular2'; 

@Component({ 
    selector: 'font-size-component', 
    properties: [ 
    'fontSize' 
    ] 
}) 
@View({ 
    template: `<input id="fontSize" class="form-control" name="fontSize" [(ng-model)]="fontSize"/>`, 
    directives: [ 
    FORM_DIRECTIVES 
    ] 
}) 

export class FontSizeComponent { 
    constructor() { 

    } 
} 
+1

實際上維克多Savkin的博客帖子只是一個如何實現的例子ng-model,angular2表單帶有FORM_DIRECTIVES中包含的一個實現。它看起來最後的編輯是好的,它是最角度的1路AFIK。有沒有按預期工作? –

回答

1

您必須初始化您的指令events事件發射器。你可以做到這一點無論是在控制器:

import { EventEmitter, Directive } from 'angular2/angular2'; 

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

    constructor() { 
     this.newModelChanged = new EventEmitter(); // <== INITIALIZATION 
    } 
} 

或者,如果您使用的是打字稿,在你的屬性定義:

// ... 
export class NgModelDirective { 
    ngModel: any; // stored value 
    ngModelChanged = new EventEmitter(); // <== INITIALIZATION 
}