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.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With