Angular 2-如何从父级触发对子级的方法 [英] Angular 2 - How to trigger a method on a child from the parent

查看:81
本文介绍了Angular 2-如何从父级触发对子级的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以通过@Input从父级向子级发送数据,或者使用@Output从子级调用父级上的方法,但是我想做另一种方法,即调用a从父级对子级的方法.基本上是这样的:

It's possible to send data from the parent to a child through @Input, or to call a method on the parent from the child with @Output, but I'd like to do exactly the other way around, which is calling a method on the child from the parent. Basically something like that:

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

和孩子:

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

  constructor() {}
}

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

Background is a kind of "get" request, i.e. for getting an up-to-date status from the child.

现在我知道我可以通过服务和Subject/Observable来实现这一目标,但是我想知道是否还没有更简单的方法?

Now I know I could achieve that with a service and Subject/Observable, but I was wondering whether there is not something more straightforward?

推荐答案

我认为这些可能是您想要的:

I think these might be what you're looking for:

https://angular.io/guide/component-interaction#parent-interacts-with-child-via-local-variable

https://angular.io/guide/component-interaction#父级通话的子视图

您可以使用模板中的局部变量或使用父级组件类中的@ViewChild装饰器来访问子级属性和方法.

You can access child properties and methods using local variables within the template or using the @ViewChild decorator in the parent's component class.

这篇关于Angular 2-如何从父级触发对子级的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆