When we pass a model
to the child component and it modifies it, the values are just reflected in the child components' local variable and not available to the parent. Can we pass values by reference from parent to child. So the changes are visible there as well.
I have implemented the same using an observable
at the service layer. But can't we pass by reference through @Input
?
Sharing data between sibling components: Sharing data between siblings can be done by using points 1 and 2. First share data between the child to parent using output decorator and EventEmitter. Once received data in parent component share it to another child component using Input decorator.
Primitive values (string
, num
, boolean
, object references) are passed by value (copied), objects and arrays are passed by reference (both components get a reference to the same object instance).
Just wrap your primitive values in objects and changes will be reflected on both sides.
Angular2 change detection won't detect changes to values in arrays or object properties (except when binding expressions address them).
Actually - there is a "trick" in Angular to allow you to pass a primitive type (like a string or a number) to a child component and have those changes emitted back to the data referenced by the parent component. This is done by creating a "output EventEmitter" whose name exactly matches the input - but suffixed with "Change". I'm not sure if this is documented anywhere in any official Angular documentation - after a cursory check I wasn't able to find this.
Anyway, the best stack overflow post that documents this technique I was able to find was this: https://stackoverflow.com/a/37855138/5692144
There is also this post - but it doesn't specifically discuss the requirement of the naming of the @Output EventEmitter: https://stackoverflow.com/a/43571004/5692144
And I've confirmed this works as described.
I'm not sure why the architects/designers of Angular haven't made this technique a "first class citizen" that doesn't require you to use to obscure/arcane naming convention (for your Output EventEmitter).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With