Javascript – Angular2 version of knockout’s computed observable

angularcomputed-observablejavascriptknockout.js

I am currently working on porting some code that I have written from Knockout to Angular2. I really like the construct of computed observables in knockout which means the results of that function are only computed when the obeservables it depends on change.

I know I can use a function in angular and it will only update the view when the results change (even though it will calculate the results many times), but my computed is doing sorting, which is why I only want the work to be done when the inputs actually change.

I've found the links below that explain how to do it with angularjs, but I'm not sure how to translate that to angular2 (typescript)

http://www.jomendez.com/2015/02/06/knockoutjs-computed-equivalent-angularjs/
KO.Computed equivalent in Angular / Breeze Initializer

Best Answer

I would consider a getter if you are using TypeScript. You could also make your Component use ChangeDetectionStrategy.OnPush to make sure the binding is only evaluated if one of the properties changed. Here is a Plunker: https://plnkr.co/edit/PjcgmFCDj8UvBR7wRJs2?p=preview

import {Component,ChangeDetectionStrategy} from 'angular2/core'

@Component({
  selector:'person',
  template:`<div>
              <div>
                  First Name
                  <input [(ngModel)]="firstName">
              </div>
              <div>
                  Last Name
                  <input [(ngModel)]="lastName">
              </div>

              {{fullName}}
          </div>`,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class Person{
  firstName = '';
  lastName = '';

  get fullName(){
    return this.firstName + ' ' + this.lastName;
  } 
}