Yan*_*aim 13 typescript angular
我有一个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() {
}
}
Run Code Online (Sandbox Code Playgroud)
现在,我希望此组件在输入更改时触发事件(使用事件绑定).
在Angular 1.XI上有几个选项(ng-change或$scope.$wacth).我正在寻找类似的解决方案,所以当输入更改时,我将能够使用eventemitter并触发fontSizeChanged事件.
谢谢,
的Yaniv
ale*_*ods 20
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);
}
}
Run Code Online (Sandbox Code Playgroud)
看看这个plnkr
(input)事件绑定:@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();
}
Run Code Online (Sandbox Code Playgroud)
看到这个plnkr
Tyl*_*den 18
您还可以使用Angular2的生命周期钩子.从文档:
ngOnChanges(changeRecord){...}
在每次更改输入属性之后以及处理内容或子视图之前调用.
请参阅https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html
只需将此方法添加到组件类:
ngOnChanges(changes: {[propertyName: string]: SimpleChange}) {
if (changes['fontSize']) { // fire your event }
}
Run Code Online (Sandbox Code Playgroud)
上面的指南包括一个Plunkr:https://angular.io/resources/live-examples/lifecycle-hooks/ts/plnkr.html
| 归档时间: |
|
| 查看次数: |
31183 次 |
| 最近记录: |