值更改时不调用ngOnChange [英] ngOnChange not called when value change

查看:115
本文介绍了值更改时不调用ngOnChange的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已设置插件

我在单击按钮时更改了对象的bool属性,并且在单击ngOnchange时应已触发,这没有发生.为什么?.它与父对象和子组件之间共享的同一对象引用有关吗?

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?

推荐答案

角度变化检测仅检查对象身份.
如果您修改对象的内容,Angular将无法识别.
如果您对某个对象或数组项的属性具有绑定,Angular将检查绑定的思想,但ngOnChanges仍然不会被调用.

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.

此设计的原因是性能.如果Angular需要进行深层对象比较,则更改检测将成为更多的性能负担.

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.

一种解决方法是复制对象或数组,以创建具有不同对象ID的新对象.角度变化检测会将其识别为变化并更新对子组件的绑定.

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);

或用于数组

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

柱塞示例

其他方法可以在子组件中实现DoCheck并自行进行比较,而不必依赖于更改检测.

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

这篇关于值更改时不调用ngOnChange的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆