Reputation: 65
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 :
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!
Upvotes: 3
Views: 3627
Reputation: 11243
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.
Upvotes: 12