Angular 2.0 and ng-model

Angular 2.0 and ng-model

本文关键字:ng-model and Angular      更新时间:2023-09-26

我正在为一个关于Angular 2迁移的演示构建一个演示应用程序。我的部分应用程序有<input ng-model="" />,我想把它改成"Angular 2的方式"。所以,我有两个选项:

    使用'formDirectives',这对我的演示来说是多余的,因为我这里没有表单,只有一些更新数据的输入
  1. 使用Victor Savkin(来自Angular 2团队)在他的(伟大的)帖子中展示的内容:

<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
}