88
votes

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.

4
sounds like the best practice for doing this is using a service and an observable dispatching the event.zpul
Your question isn't too dissimilar from this one: stackoverflow.com/questions/35560860/…freethebees
@freethebees Maybe the solution is the same, but the shape of problem is different and my intent is to find the best approach to this situation.Hamed Hamedi
We're not going to setup a service for a single event passed to a child component.Ben Racicot

4 Answers

106
votes

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:

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

117
votes

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();
  }
}
14
votes

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.

0
votes

For those who are getting Cannot read property 'notifyMe' of undefined

Try calling the method inside ngAfterViewInit() intead of ngOnInit()