Ken Ken - 3 months ago 231
AngularJS Question

Angular2: child component access parent class variable/function

I have a variable in the parent component that might be changed by child, parent will be using this variable in the view and thus has to propagate changes.

import {Component, View} from 'angular2/core';

@Component({selector: 'parent'})
@View({
directives: [Child],
template: `<childcomp></childcomp>`
})
class Parent {
public sharedList = new Array();
constructor() {
}
}


@Component({selector: 'child'})
@View({template: `...`})
class Child {
constructor() {
//access 'sharedList' from parent and set values
sharedList.push("1");
sharedList.push("2");
sharedList.push("3");
sharedList.push("4");
}
}

Answer

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.

Comments