孩子在Angular 2中听父母事件 [英] Child listens for parent event in Angular 2

查看:160
本文介绍了孩子在Angular 2中听父母事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在角度文档中,有一个关于听父母的儿童事件的话题。没关系。但我的目的是反向的!在我的应用程序中有一个'admin.component',它包含管理页面的布局视图(侧边栏菜单,任务栏,状态等...)。
在这个父组件中,我配置了路由器系统,用于更改管理员其他页面之间的主视图。
问题是在更改后保存内容,用户单击任务栏中的保存按钮(位于admin.component中),子组件必须侦听该click事件以执行保存人员。

In angular docs there is a topic about listening for child events from parents. That's fine. But my purpose is something reverse!. In my app there is an 'admin.component' that holds the layout view of admin page (sidebar menu,task bar, status etc..). In this parent component I configured router system for changing the main view between other pages of administrator. The problem is for saving things after change, the user clicks on save button in task bar (that is placed in admin.component) and the child component must listen to that click event for doing save staff.

推荐答案

我认为这个文档对您有所帮助:

I think that this doc could be helpful to you:

  • https://angular.io/docs/ts/latest/cookbook/component-communication.html

事实上,您可以利用父母为其提供的可观察/主题儿童。类似的东西:

In fact you could leverage an observable / subject that the parent provides to its children. Something like that:

@Component({
  (...)
  template: `
    <child [parentSubject]="parentSubject"></child>
  `,
  directives: [ ChildComponent ]
})
export class ParentComponent {
  parentSubject:Subject<any> = new Subject();

  notifyChildren() {
    this.parentSubject.next('some value');
  }
}

子组件可以简单地订阅此主题:

The child component can simply subscribe on this subject:

@Component({
  (...)
})
export class ChildComponent {
  @Input()
  parentSubject:Subject<any>;

  ngOnInit() {
    this.parentSubject.subscribe(event => {
      // called when the notifyChildren method is
      // called in the parent component
    });
  }

  ngOnDestroy() {
    // needed if child gets re-created (eg on some model changes)
    // note that subsequent subscriptions on the same subject will fail
    // so the parent has to re-create parentSubject on changes
    this.parentSubject.unsubscribe();
  }

}

否则,您可以利用共享以类似方式包含此类主题的服务......

Otherwise, you could leverage a shared service containing such a subject in a similar way...

这篇关于孩子在Angular 2中听父母事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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