Yaniv Efraim Yaniv Efraim - 7 months ago 22
Javascript Question

Change detection in Angular 2.0

I have an Angular2.0 component:

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() {

}
}


Now, I want this component to trigger an event (using event-binding) when the input changes.

On Angular 1.X I had several options (
ng-change
or
$scope.$wacth
). I am looking for a similar solution, so when the input changes I will be able to use
eventemitter
and trigger an
fontSizeChanged
event.

Thanks,

Yaniv

Answer
  1. You can use javascript getters and setters. So your component would look like:
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);
    }
}

Check out this plnkr

  1. Slightly different solution is to use (input) event binding:
@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();
}

See this plnkr