繁体   English   中英

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

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

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

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

背景是一种“获取”请求,即从孩子获得最新状态。

现在我知道我可以通过服务和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装饰器来访问子属性和方法。

@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!
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM