我有一个父组件和一个子组件.我希望能够从父组件上的某个方法调用子组件上的一些子方法.有没有办法获得父类的子组件实例的引用并调用子的公共方法?
@Component({
selector: 'child-component'
})
@View({
template: `<div>child</div>`
})
class ChildComponent{
constructor () {
}
doChildEvent () {
// some child event
}
}
@Component({
selector: 'parent-component'
})
@View({
template: `
<child-component #child></child-component>
`,
directives: [
ChildComponent
]
})
class ParentComponent {
private child:ChildComponent;
constructor () {
}
onSomeParentEvent() {
this.child.doChildEvent();
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试在模板中对子进行哈希并在类中引用它但没有成功.
这ViewChild是为了什么:
//don't forget to import ViewChild
class ParentComponent {
@ViewChild(ChildComponent) private child:ChildComponent;
constructor () {
//this.child is undefined because constructor is called before AfterViewInit
}
onSomeParentEvent() {
//this.child contains the reference you're looking for
this.child.doChildEvent();
}
}
Run Code Online (Sandbox Code Playgroud)
假设在onSomeParentEvent被激活之后AfterViewInit,
this.child将包含对子组件的引用.
| 归档时间: |
|
| 查看次数: |
595 次 |
| 最近记录: |