Reputation: 18513
In Angular 2 how do you access a child component class from the parent component class? e.g.
import {Component, View} from 'angular2/core';
@Component({selector: 'child'})
@View({template: `...`})
class Child {
doSomething() {
console.log('something');
}
}
@Component({selector: 'parent'})
@View({
directives: [Child],
template: `<child></child>`
})
class Parent {
constructor() {
//TODO: call child.doSomething() when the child component is ready
}
}
In this example how would I call the Child
component's doSomething()
method from either the Parent
component's constructor or some callback function.
Upvotes: 4
Views: 3652
Reputation: 1484
You can use @ViewChild
in you parent component to accesss any methods of child components.
@Component({
selector: 'parent',
directives: [Child]
})
export class Parent {
@ViewChild(Child) childComponent: Child;
ngAfterViewInit() {
// The child is available here
childComponent.doSomething();
}
}
Note: This code snippet is for angular2 rc4 version.
Upvotes: 1
Reputation: 31777
It's quite simple but you have to keep a few points in mind which I'll detail below, first the code.
To reference your children, in this case you want your children within your View, so you must use @ViewChildren
and you must wait the view to be initialized so you do
@Component({
selector: 'hello',
template: `<child></child>`,
directives : [Child]
})
export class Parent implements AfterViewInit {
@ViewChildren(Child) children: QueryList<Child>;
afterViewInit() {
for(let child of this.children) {
child.doSomething();
}
}
}
Note
The loop inside afterViewInit()
will work if you are transpiling to ES6 since angular2 internally uses Symbol.iterator
. If you are transpiling to ES5 you'll have to workaround it since typescript does not support it (see plnkr for workaround).
Here's the plnkr.
I hope it helps :)
Upvotes: 7