【问题标题】:Execute method on child component子组件的执行方法
【发布时间】:2017-04-21 21:22:42
【问题描述】:

我有一个父组件和一个子组件。我希望能够从父组件上的某个方法调用子组件上的某个子方法。 有没有办法在父类上获取对子组件实例的引用并调用子类的公共方法?

@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();
    }
}

我尝试在模板中对孩子进行哈希处理并在课堂上引用它,但没有成功。

【问题讨论】:

  • #child - 这些本地模板变量不会成为组件的属性(如您所见)。我在文档中找不到有关其范围的任何内容(而且我不想查看源代码)。看来他们的范围仅限于模板。

标签: angular typescript


【解决方案1】:

这就是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();
    }
}

假设onSomeParentEventAfterViewInit 之后被解雇, this.child 将包含对子组件的引用。

【讨论】:

  • 正是我想要的!
猜你喜欢
  • 2017-01-04
  • 2017-04-12
  • 1970-01-01
  • 2022-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-17
相关资源
最近更新 更多