5

First I had just this in my ngDoCheck method and works perfectly:

var productChanges = this.differ.diff(this.myProduct);

then decided to check changes on a second model of my component and added this below line:

var companyChanges = this.differ.diff(this.myCompany);

and both changes are chekeced in separate if statements but only last one gets called (companyChanges)

Is this expected behavior? Does ngDoCheck only works for one object per component?

For the sake of clarity here is my full ngDoCheck method:

ngDoCheck() {
    var productChanges = this.differ.diff(this.myProduct);

    //DOESN'T IT CHECK 2 MODELS LIKE SO BELOW ?
    //var companyChanges = this.differ.diff(this.myCompany);

    if (productChanges) {
        // console.log('Product changes detected');

        productChanges.forEachChangedItem((r: KeyValueChangeRecord) => {

            if (r.currentValue && r.currentValue != r.previousValue) {
                this.filterProduct(r.currentValue, r.key);

            }
        });
    }

EDIT: by reading other questions and answers I feel I need to share this:

In component constructor differ is defined like so:

this.differ = differs.find({}).create(null);

Probably this is what needs to be changed first.

Bogac
  • 3,596
  • 6
  • 35
  • 58

1 Answers1

9

After reading answer from @thierry-templier for this question: Detect changes in objects inside array in Angular2 I've figured how it works:

Class level differ object shall contain separate keys for each model to be watched and as for their value they need to be set separate differ watcher referencing each model respectively, in ngOnInit or constructor. (Thierry did it in ngOnInit, I did it in constructor)

constructor(private differs: KeyValueDiffers){
    this.differ = {};

    this.differ['myCompany'] = differs.find(this.myCompany).create(null);
      .
      .
      .
    this.differ['myProduct'] = differs.find(this.myProduct).create(null);
}

ngDoCheck() {
    var productChanges = this.differ['myProduct'].diff(this.myProduct);
    var companyChanges = this.differ['myCompany'].diff(this.myCompany);

    if (productChanges) {
        // Do your thing 
    }

    if (companyChanges) {
        // Do your thing 
    }
}
Community
  • 1
  • 1
Bogac
  • 3,596
  • 6
  • 35
  • 58