在Angular 2.0中更改检测

时间:2015-08-30 10:38:51

标签: angular typescript

我有一个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事件。

谢谢,

参见Yaniv

3 个答案:

答案 0 :(得分:20)

  1. 您可以使用javascript getterssetters。所以你的组件看起来像:
  2. 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)事件绑定:
    2. @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

答案 1 :(得分: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 }
}

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

答案 2 :(得分:2)

如果您想手动处理对输入的更改,可以通过执行以下操作来分离短手[(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

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