Hamed Hamedi Hamed Hamedi - 1 year ago 835
Javascript Question

Child listens for parent event in Angular 2

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.

Answer Source

I think that this doc could be helpful to you:

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

  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:

export class ChildComponent {

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download