在子组件上执行方法
Execute method on child component
我有一个父组件和一个子组件。我希望能够从父组件上的某个方法调用子组件上的某个子方法。
有没有办法在父组件的 class 上获取对子组件实例的引用并调用子组件的 public 方法?
@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();
}
}
我尝试在模板中对子项进行哈希处理并在 class 中引用它,但没有成功。
这就是 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();
}
}
假设 onSomeParentEvent
在 AfterViewInit
之后触发,
this.child
将包含对子组件的引用。
我有一个父组件和一个子组件。我希望能够从父组件上的某个方法调用子组件上的某个子方法。 有没有办法在父组件的 class 上获取对子组件实例的引用并调用子组件的 public 方法?
@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();
}
}
我尝试在模板中对子项进行哈希处理并在 class 中引用它,但没有成功。
这就是 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();
}
}
假设 onSomeParentEvent
在 AfterViewInit
之后触发,
this.child
将包含对子组件的引用。