我有一个 Angular2.0 组件:
import {Component, View, FORM_DIRECTIVES} from 'angular2/angular2';
@Component({
selector: 'font-size-component',
properties: ['fontSize'],
events: ['fontSizeChanged']
})
@View({
template: `<input id="fontSize" [(ng-model)]="fontSize"/>`,
directives: [FORM_DIRECTIVES]
})
export class FontSizeComponent {
constructor() {
}
}
现在,我希望此组件在输入更改时触发一个事件(使用事件绑定(bind))。
在 Angular 1.X 上,我有几个选项(ng-change
或 $scope.$wacth
)。我正在寻找类似的解决方案,因此当输入发生变化时,我将能够使用 eventemitter
并触发 fontSizeChanged
事件。
谢谢,
亚尼夫
最佳答案
import {Component, View, FORM_DIRECTIVES, EventEmitter} from 'angular2/angular2';
@Component({
selector: 'font-size-component',
properties: ['fontSize'],
events: ['fontSizeChange']
})
@View({
template: `
<input id="fontSize" [(ng-model)]="fontSizeModel"/>
`,
directives: [FORM_DIRECTIVES]
})
export class FontSizeComponent {
fontSize: string;
fontSizeChange = new EventEmitter();
get fontSizeModel() {
return this.fontSize;
}
set fontSizeModel(value) {
this.fontSizeChange.next(value);
}
}
查看 this plnkr
- 稍微不同的解决方案是使用
(input)
事件绑定(bind):
@Component({
selector: 'font-size-component',
properties: ['fontSize'],
events: ['fontSizeChange']
})
@View({
template: `
<input
id="fontSize"
[value]="fontSize"
(input)="fontSizeChange.next($event.target.value)"
/>
`,
directives: [FORM_DIRECTIVES]
})
export class FontSizeComponent {
fontSize: string;
fontSizeChange = new EventEmitter();
}
参见 this plnkr
关于angular - Angular 2.0 中的变更检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32295635/