Angular 2.0 中的更改检测

Change detection in Angular 2.0

我有一个 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() {

  }
}

现在,我希望此组件在输入更改时触发一个事件(使用事件绑定)。

在 Angular 1.X 我有几个选择(ng-change$scope.$wacth)。我正在寻找类似的解决方案,因此当输入发生变化时,我将能够使用 eventemitter 并触发 fontSizeChanged 事件。

谢谢,

亚尼夫

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

  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();
}

this plnkr

您还可以利用 Angular2 的生命周期挂钩。来自文档:

ngOnChanges(changeRecord) { ... }
Called after every change to input properties and before processing content or child views.

https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html

只需将此方法添加到您的组件中即可 class:

ngOnChanges(changes: {[propertyName: string]: SimpleChange}) {
  if (changes['fontSize']) { // fire your event }
}

上面的指南包括一个 Plunkr: https://angular.io/resources/live-examples/lifecycle-hooks/ts/plnkr.html

如果您想手动处理对输入的更改,您可以通过执行以下操作来分离简写 [(ngModel)]:

<input id="fontSize" [ngModel]="fontSize" (ngModelChange)="fontSizeChange($event)"/>

确保在 fontSizeChange($event) 函数中使用 $event 将更改的输入值分配给 fontSize 变量,因为这不再自动处理。

当你使用 [(ngModel)] 时,它实际上是在做这样的事情:

<input id="fontSize" [ngModel]="fontSize" (ngModelChange)="fontSize=$event" />

更多信息可以参考官方文档:https://angular.io/docs/ts/latest/guide/template-syntax.html#!#two-way-binding-with-ngmodel

目前 Angular2 仍处于测试阶段,因此可能会发生变化。