Reputation: 7
Pass an object to the child component. <child [model]="parentModel">
Make change to a certain property in the object in the child component. Will this change now be visible in the parent component?
As per my knowledge, change will not be reflected, if we are passing numbers, strings, boolean but if pass objects, change should be visible in the parent component (As we are passing it like a reference)
Upvotes: 0
Views: 1397
Reputation: 1976
Yes, As long as same reference and mutable, You will get the updated value in parant component.
Playground: Parent-Child-Obj-Ref
Upvotes: 0
Reputation: 2992
When you pass a reference type value from parent
to child
it means either of your components would work with the same value. So it will work with all changes of your reference value. Reference type can be not only an object
, but also an array
structure.
Another question is how your parent
component knows when to redraw a view to show changes in the value. That problem can be solved by change detection system in Angular
.
If your changes trigger event in the parent
component then you no need to worry about - change detection will do everything itself. If not, then you have to know when to trigger detectChanges
method of ChangeDetectorRef
service in parent
component. For example, it can be done with @Output
decorator in child component, or you can even inject ChangeDetectorRef
with option SkipSelf
to the child
and trigger detectChanges
method there, when object changes... there are lot of possibilities to solve this problem.
Upvotes: 0
Reputation: 775
In Angular, you can pass an object to a child component as a property. If you want changes made to the object in the child component to be reflected in the parent component, you need to ensure that the object is mutable.
When you pass an object as an input to a child component in Angular, the reference to the object is passed, not a copy of the object. So, any changes made to the object in the child component will be reflected in the parent component, because they are modifying the same object.
Upvotes: 2