3

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!

1 Answer 1

12

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.
Sign up to request clarification or add additional context in comments.

1 Comment

@Paul - Feel free to mark the answer as accepted (with the green check mark) if it solved your problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.