If you use input property databinding with a JavaScript reference type (e.g., Object, Array, Date, etc.), then the parent and child will both have a reference to the same/one object. Any changes you make to the shared object will be visible to both parent and child.
In the parent's template:
<child [aList]="sharedList"></child>
In the child:
@Input() aList;
...
updateList() {
this.aList.push('child');
}
If you want to add items to the list upon construction of the child, use the ngOnInit()
hook (not the constructor(), since the data-bound properties aren't initialized at that point):
ngOnInit() {
this.aList.push('child1')
}
This Plunker shows a working example, with buttons in the parent and child component that both modify the shared list.
Note, in the child you must not reassign the reference. E.g., don't do this in the child: this.aList = someNewArray;
If you do that, then the parent and child components will each have references to two different arrays.
If you want to share a primitive type (i.e., string, number, boolean), you could put it into an array or an object (i.e., put it inside a reference type), or you could emit()
an event from the child whenever the primitive value changes (i.e., have the parent listen for a custom event, and the child would have an EventEmitter
output property. See @kit's answer for more info.)
Update 2015/12/22: the heavy-loader
example in the Structural Directives guides uses the technique I presented above. The main/parent component has a logs
array property that is bound to the child components. The child components push()
onto that array, and the parent component displays the array.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…