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.
ngDoCheck life-cycle hook Simply put, Angular tracks binding inputs by object reference. It means that if an object reference hasn't changed, the binding change is not detected and change detection is not executed.
ngOnChanges() ( OnChanges ) is called when a value bound to an input has changed so you can run custom code when an input has changed. ngDoCheck() ( DoCheck ) is called when change detection runs so you can implement your custom change detection action.
ngDoCheck()link mode_edit code. A callback method that performs change-detection, invoked after the default change-detector runs. See KeyValueDiffers and IterableDiffers for implementing custom change checking for collections.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With