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

Chr*_*dal 48 components input typescript output angular

可以通过@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实现这一点,但我想知道是否有更直接的东西?

awi*_*man 56

我想这些可能就是你要找的东西:

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

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

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

  • @Pascal对于具有多个子组件实例的情况,您应该使用ViewChildren装饰器.https://angular.io/docs/ts/latest/api/core/index/ViewChildren-decorator.html (2认同)

mpr*_*pro 23

@ViewChild 是正确的解决方案,但上面链接的文档对我来说有点不清楚,所以我传递了一些更友好的解释,这有助于我理解它.

我们有ChildComponent一个方法:

whoAmI() {
  return 'I am a child!!';
}
Run Code Online (Sandbox Code Playgroud)

和父组件一起,我们可以使用'@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!
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果同一组件类有多个实例怎么办?据我所尝试和看到的,这会触发该类的第一个实例吗? (2认同)