Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2: Pass by reference to interact between components

When we pass a modelto 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?

like image 700
Sumit Agarwal Avatar asked Oct 26 '16 10:10

Sumit Agarwal


People also ask

How do you pass data between two child components?

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.


2 Answers

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).

like image 108
Günter Zöchbauer Avatar answered Oct 12 '22 08:10

Günter Zöchbauer


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).

like image 2
Tim Avatar answered Oct 12 '22 08:10

Tim