【问题标题】:Angular 2 - How to trigger a method on a child from the parentAngular 2 - 如何从父级触发子级的方法
【发布时间】:2016-10-04 18:16:08
【问题描述】:

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

【问题讨论】:

标签: angular typescript input components output


【解决方案1】:

我认为这些可能是您正在寻找的:

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 装饰器是否也可以工作?我只有一个孩子的实例对吗?
  • @Pascal 对于具有多个子组件实例的情况,您应该使用 ViewChildren 装饰器。 angular.io/docs/ts/latest/api/core/index/…
【解决方案2】:

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

【讨论】:

  • 如果同一个组件类有多个实例怎么办?据我所见,这会触发该类的第一个实例?
  • 上面有评论回答这个问题,但为了完整起见……@ViewChildren 是一回事。 ?
  • 另外,对这个答案的一个小修正——你需要使用ngAfterViewInit而不是ngOnInit
猜你喜欢
  • 1970-01-01
  • 2017-03-25
  • 2016-11-12
  • 2017-04-09
  • 1970-01-01
  • 2017-07-20
  • 2015-07-28
  • 1970-01-01
  • 2018-01-15
相关资源
最近更新 更多