Child listens for parent event in Angular 2

Solution 1:

For the sake of posterity, just thought I'd mention the more conventional solution to this: Simply obtain a reference to the ViewChild then call one of its methods directly.

@Component({
  selector: 'app-child'
})
export class ChildComponent {

  notifyMe() {
    console.log('Event Fired');
  }
}

@Component({
  selector: 'app-parent',
  template: `<app-child #child></app-child>`
})
export class ParentComponent {

  @ViewChild('child')
  private child: ChildComponent;

  ngOnInit() {
    this.child.notifyMe();
  }
}

Solution 2:

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...

Solution 3:

A more bare bones approach might be possible here if I understand the question correctly. Assumptions --

  • OP has a save button in the parent component
  • The data that needs to be saved is in the child components
  • All other data that the child component might need can be accessed from services

In the parent component

<button type="button" (click)="prop1=!prop1">Save Button</button>
<app-child-component [setProp]='prop1'></app-child-component>

And in the child ..

prop1:boolean;
  @Input()
  set setProp(p: boolean) {
    // -- perform save function here
}

This simply sends the button click to the child component. From there the child component can save the data independently.

EDIT: if data from the parent template also needs to be passed along with the button click, that is also possible with this approach. Let me know if that is the case and I will update the code samples.