我正在构建一个关于Angular 2迁移的演示文稿的演示应用程序。我的应用程序的一部分有<input ng-model="" />
,我想将其更改为&#34; Angular 2的方式&#34;。
所以,我有两个选择:
<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 is working],但是事件绑定不起作用,给出以下错误:
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
时,所有错误都会消失......
我对Angular 2很新(我们大概都是这样),并试着理解我在这里做错了什么......
修改
好的,所以在reading再多一点后,我确信使用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() {
}
}
答案 0 :(得分: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
}
}
或者,如果您在属性定义中使用TypeScript:
// ...
export class NgModelDirective {
ngModel: any; // stored value
ngModelChanged = new EventEmitter(); // <== INITIALIZATION
}