How to listen for value changes from class property TypeScript - Angular

L Y E S  -  C H I O U K H picture L Y E S - C H I O U K H · Mar 29, 2018 · Viewed 53.6k times · Source

In AngularJS, we can listen variable change using $watch, $digest... which is no longer possible with the new versions of Angular (5, 6).

In Angular, this behaviour is now part of the component lifecycle.

I checked on the official documention, articles and especially on Angular 5 change detection on mutable objects, to find out how to listen to a variable (class property) change in a TypeScript class / Angular

What is proposed today is :

This is only true for @Input() property !

If I want to track changes of my component's own properties (myProperty_1, myProperty_2 or myProperty_3), this will not work.

Can someone help me to solve this problematic ? Preferably a solution that is compatible with Angular 5

Answer

Pengyy picture Pengyy · Mar 29, 2018

You can still check component's field members value change by KeyValueDiffers via DoCheck lifehook.

import { DoCheck, KeyValueDiffers, KeyValueDiffer } from '@angular/core';

differ: KeyValueDiffer<string, any>;
constructor(private differs: KeyValueDiffers) {
  this.differ = this.differs.find({}).create();
}

ngDoCheck() {
  const change = this.differ.diff(this);
  if (change) {
    change.forEachChangedItem(item => {
      console.log('item changed', item);
    });
  }
}

see demo.