ngOnChange not called when value change

前端 未结 1 1708
抹茶落季
抹茶落季 2021-01-05 21:53

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?

相关标签:
1条回答
  • 2021-01-05 22:44

    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.

    0 讨论(0)
提交回复
热议问题