marcel marcel - 5 months ago 107
TypeScript Question

Angular2 watch object/array changes (Angular2 final >= 2.1.1)

I'd like to watch an object/array, which ca be edited by a service or by a controllers routine. I thought that an Observable could watch an object/array.

My implementation doesn't react on changes of the items :

private data : Observable<Array<any>>;
private dataObserver: Observer<Array<any>>;
private sub : Subscription;
private items: <Array<any>>;

ngOnInit() {
this.items = itemService.getItems(); = new Observable<Array<any>>(observer =>{
this.dataObserver = observer;
x => console.log('onNext: %s', x),
e => console.log('onError: %s', e),
() => console.log('onCompleted')

private start(){

//change values of the array in an interval
let loop = Observable.interval(250)
let i=0;
self.sub = loop.subscribe(() => {
self.items[0].id= i;
if(i<100) i++;
else i=1;

The observalbes subsciption doesn't react on changes of the items array. It only triggers on its next mehtod. On the other hand .. this is too cumbersome for a simple watch method.

What does angular-2 offer us to watch for changes, as $scope.$watch did in angular-1?


Angular2 provides IterableDiffer (array) and KeyValueDiffer (object) to get information about differences between two checks.

NgClass is a good example

See also!?query=differ

An example

// inject a differ implementation 
constructor(differs: KeyValueDiffers) {
  // store the initial value to compare with
  this.differ = differs.find({}).create(null);

@Input() data: any;

ngDoCheck() {
  var changes = this.differ.diff(; // check for changes
  if (changes && this.initialized) {
    // do something if changes were found