我正在为有关 Angular 2 迁移的演示构建一个演示应用程序。我的应用程序的一部分有 <input ng-model="" />
我想将其更改为“Angular 2 的方式”。
所以,我有两个选择:
- 使用“formDirectives”,这对我的演示来说有点矫枉过正,因为我这里没有表单,只有一些输入更新了一些数据
- 使用 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() {
}
}
我的输入正在使用提供的数据呈现(属性绑定(bind) [ng-model 正在工作],但事件绑定(bind)不起作用,出现以下错误:
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() {
}
}
最佳答案
您必须为指令初始化 events
事件发射器。您可以在 Controller 中执行此操作:
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
}
关于javascript - Angular 2.0 和 ng-model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32294361/