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

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

问题描述

在 angular 文档中有一个关于从父母那里侦听子事件的主题.没关系.但我的目的是相反的!.在我的应用程序中有一个admin.component",它包含管理页面的布局视图(侧边栏菜单、任务栏、状态等).在这个父组件中,我配置了路由器系统以在管理员的其他页面之间更改主视图.问题是为了在更改后保存东西,用户点击任务栏中的保存按钮(放置在 admin.component 中),子组件必须监听该点击事件才能保存员工.

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:

事实上,您可以利用父级提供给其子级的 observable/subject.类似的东西:

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天全站免登陆