简体   繁体   中英

Angular : Updating property of passed object in child component updates parent component, updating its value doesn't, why?

There's a behavior in Angular I don't really understand. Let's say I've two components : a parent and a child. The parent component passes data to the child.

In the child component :

  • When properties of the passed object are updated, the object updates both in parent and child component .
  • When the object value is updated, the parent component does not update .

I don't know if I made it clear, so I made this plunker :

http://next.plnkr.co/edit/PnlotZxt3DLbAGAF?open=lib%2Fapp.ts&deferRun=1&preview

Hit "Update Salary" to update the salary property of the employee object. Hit "Update Employee" to update the employee object value.

Can someone please explain me this behavior ? I though using bracket and @Input() was for one-way data binding only and now I'm confused.

Thank you!

Its matter of reference of Object. The changes can be detect as long as object are has the same reference.

In your case - You are assigning the new value to employee in child component which breaks the chain. Now the Parent is pointing to different employee object and child is referring to different employee .

In short you always need to make sure that you can change the property of object but should not reassign ( reference change ) to other object.

In your example I had modified the change from

this.employee = this.employee2;

to

Object.assign(this.employee,this.employee2);  // this will change the existing object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM