Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngOnChange not called when value change

Tags:

angular

I have setup plunk

I am changing bool property of object on click of button and on click ngOnchange should have triggered which is not happening. Why?. Is it related to same object reference is shared between parent and child component?

like image 471
Praveen Rawat Avatar asked Oct 12 '17 05:10

Praveen Rawat


1 Answers

Angular change detection only checks object identity.
If you modify the content of an object, Angular won't recognize.
If if you have a binding to a property of an object or item of an array, Angular will check the binding thought, but ngOnChanges still won't be called.

This reason for this design is performance. Change detection would become much more of a performance burden if Angular would need to do deep object comparison.

A workaround is to copy the object or array, to create a new object with a different object id. Angular change detection will recognize it as change and update the binding to the child component.

  this.data.status = !this.data.status
  this.data = Object.assign({}, this.data);

or for array

  this.data = this.data.slice();

Plunker example

Other ways are implementing DoCheck in the child component and do the comparison yourself instead of depending on change detection.

like image 102
Günter Zöchbauer Avatar answered Oct 29 '22 15:10

Günter Zöchbauer