在Angular 2.0中更改检测

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

  1. 您可以使用javascript gettersetter.所以你的组件看起来像:
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

  1. 稍有不同的解决方案是使用(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

  • 哇 - 这是一个很棒的**答案,非常感谢你!一个问题 - 在您的第一个示例中,我无法看到如何使用传入的"fontSize"(属性绑定)数据初始化输入.关于第二个例子 - 是`(输入)`相当于`ng-change()`(我正在寻找(: (2认同)

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