Angular 2 - 如何从 parent 触发 child 上的方法

Angular 2 - How to trigger a method on a child from the parent

可以通过@Input 将数据从parent 发送到child,或者使用@Output 从child 调用parent 上的方法,但我想完全相反,即从 parent 调用 child 上的方法。基本上是这样的:

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

和 child:

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

  constructor() {}
}

后台是一种 "get" 请求,即从 child.

获取 up-to-date 状态

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

我认为这些可能是您要查找的内容:

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

https://angular.io/guide/component-interaction#parent-calls-an-viewchild

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

@ViewChild 是正确的解决方案,但上面链接的文档对我来说有点不清楚,所以我通过了更友好的解释,帮助我理解它。

让我们有一个 ChildComponent 方法:

whoAmI() {
  return 'I am a child!!';
}

以及父组件,我们可以在其中使用“@ViewChild”技术调用上面的方法:

import { Component, ViewChild, OnInit } from '@angular/core';

import { ChildComponent } from './child.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {

  @ViewChild(ChildComponent) child: ChildComponent;

  ngOnInit() {
    console.log(this.child.whoAmI()); // I am a child!
  }
}