Angular 2.0 和 ng-模型

Angular 2.0 and ng-model

我正在为有关 Angular 2 迁移的演示构建一个演示应用程序。我的应用程序的一部分有 <input ng-model="" />,我想将其更改为 "Angular 2's way"。 所以,我有两个选择:

  1. 使用 'formDirectives',这对我的演示来说有点矫枉过正,因为我这里没有表格,只有一些输入更新了一些数据
  2. 使用 Victor Savkin(形成 Angular 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-model 正在运行],但事件绑定不起作用,出现以下错误:

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

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

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

当我从 ng-model 指令中删除这一行 events: ['ngModelChanged: ngModel'], 时,所有错误都消失了...

我是 Angular 2 的新手(我们可能都是新手)并尝试了解我在这里做错了什么...

编辑

好的,所以在 多一点之后,我确信使用 formDirectives 并不过分。我的解决方案是(使用 Angular 2 Alpha 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() {

  }
}

您必须为指令初始化 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
    }
}

或者,如果您使用的是 TypeScript,请在​​您的属性定义中:

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