If you use data binding of input properties with JavaScript reference type (for example, Object, Array, Date, etc.), then the parent and child will have a link to the same / same object. Any changes made to the shared object will be visible to both parents and children.
In the parent template:
<child [aList]="sharedList"></child>
The child has:
@Input() aList; ... updateList() { this.aList.push('child'); }
If you want to add items to the list when building the child, use ngOnInit() (not the constructor (), because the data properties are not initialized at this point):
ngOnInit() { this.aList.push('child1') }
This Plunker shows a working example with buttons in the parent and child components that modify the general list.
Please note that in the case of a child, you should not reassign the link. For example, do not do this in the child: this.aList = someNewArray; If you do this, the parent and child components will have references to two different arrays.
If you want to share a primitive type (i.e. string, number, boolean), you can put it in an array or object (i.e. put it inside a reference type) or you could emit() event from a child when it changes primitive value (i.e. parent listens for a custom event, and the child will have an EventEmitter output EventEmitter . See @kit answer for more information.)
Update 2015/12/22: the heavy-loader example in the Structural Directives uses the technique I presented above. The main / parent component has a logs array property associated with child components. Detailed components push() to this array, and the parent component maps the array.
Mark Rajcok Dec 10 '15 at 17:48 2015-12-10 17:48
source share