小编Chr*_*dal的帖子

Angular 2 - 如何从父级触发子对象的方法

可以通过@Input将数据从父节点发送给子节点,或者通过@Output从子节点调用父节点上的方法,但是我想完全相反,这就是调用方法来自父母的孩子.基本上是这样的:

@Component({
  selector: 'parent',
  directives: [Child],
  template: `
<child
  [fn]="parentFn"
></child>
`
})
class Parent {
  constructor() {
    this.parentFn()
  }
  parentFn() {
    console.log('Parent triggering')
  }
}
Run Code Online (Sandbox Code Playgroud)

和孩子:

@Component({
  selector: 'child',
  template: `...`
})
class Child {
  @Input()
  fn() {
    console.log('triggered from the parent')
  }

  constructor() {}
}
Run Code Online (Sandbox Code Playgroud)

背景是一种"获取"请求,即从孩子获得最新状态.

现在我知道我可以通过服务和Subject/Observable实现这一点,但我想知道是否有更直接的东西?

components input typescript output angular

48
推荐指数
2
解决办法
5万
查看次数

标签 统计

angular ×1

components ×1

input ×1

output ×1

typescript ×1