93

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.

Hamed Hamedi
  • 1,461
  • 1
  • 10
  • 19
  • 2
    sounds like the best practice for doing this is using a service and an observable dispatching the event. – zpul Jun 07 '16 at 10:52
  • Your question isn't too dissimilar from this one: http://stackoverflow.com/questions/35560860/in-angular2-how-to-let-child-components-communicate-with-each-other – freethebees Jun 07 '16 at 10:58
  • @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 Jun 07 '16 at 11:57
  • We're not going to setup a service for a single event passed to a child component. – Ben Racicot Feb 14 '19 at 17:36

4 Answers4

128

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();
  }
}
Stephen Paul
  • 37,253
  • 15
  • 92
  • 74
  • 3
    It crashes as soon as I enter the parent component... `Cannot read property 'notifyMe' of undefined`. – kind user Feb 24 '17 at 16:23
  • Hm, apparently your child component is not being set by Angular. Make sure that ChildComponent has the correct selector. – Stephen Paul Feb 24 '17 at 16:26
  • Awesome, unlike the accepted answer this solution doesn't require any extra lib (even though RxJS is standard for Angular2 =)) – jwanglof Feb 24 '17 at 23:35
  • When the child component is initialized after the parent component, my child reference is undefined. Is there a way to wait for it to be initialized before assigning the ViewChild? – cjsimon Jun 01 '17 at 16:40
  • I tried for a day to get a child component to get updated by its parent component via subscribing to a shared service with no luck, this solution is so simple! Thank you! – user3777549 Sep 18 '17 at 17:06
  • multiple child using same commponent then this will fail – Lijo Sep 24 '17 at 21:18
  • @Lijo good point. It's been a while since I looked at this. Updated my ViewChild() decorator to rather target the #id rather than the component type. – Stephen Paul Sep 25 '17 at 11:54
  • 1
    Went for this very straighforward solution as compared to the somehow more professional feeling solution of @ThierryTemplier (see my comment there). – Youp Bernoulli Mar 10 '18 at 14:49
  • 2
    @BernoulliIT you make a good point. I suppose at the end of the day they accomplish roughly the same thing. My solution uses less code. His solution means that the parent component doesn't have to inject the child component to send it messages. RXJS is great, but I do often see overuse of it within Angular projects. People think its this 'silver bullet' or something. It can actually make things much more complicated than they need to be. Look at his comment inside his `ngOnDestroy()` method. That's way too obscure as far as I'm concerned. That's just a bug waiting to happen IMHO. – Stephen Paul Mar 10 '18 at 18:12
  • 1
    "Look at his comment inside his ngOnDestroy() method." I think that's exactly what I was "suffering" from when trying that approach, then I got stuck and didn't have that much time to investigate any further (for a commercial project I work on). Although it "hurted' my professional heart a bit ;) – Youp Bernoulli Mar 12 '18 at 08:49
  • 1
    Thanks @StephenPaul, for me [Parent Calls a Viewchild](https://angular.io/guide/component-interaction#parent-calls-an-viewchild) method was good, but your answer helped me to reach my destiny! – Khuram Mar 22 '18 at 10:44
112

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

Arnaud P
  • 12,022
  • 7
  • 56
  • 67
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • The callback in my child component won't run unless the parent component broadcasts the next value from within ngInit. Why is that the case? – cjsimon Apr 27 '17 at 02:43
  • 5
    Are there any advantages of using this method over ViewChild? – sundeepg Aug 01 '17 at 13:29
  • Although it looks more professional, after giving it some hours to experiment with in my situation I couldn't get out of trouble with UnsubscribeErrors upon adding / removing child elements (and thus unsubscribing from the topic). So by means of TimeBoxing I went for the much more straightforward answer of @StephenPaul. Anyway thanks for the answer and probably I just don't get the rxjs library well enough right now to fully understand it and make the right (extra) adjustments to your example to have it work flawless. – Youp Bernoulli Mar 10 '18 at 14:47
16

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.

charsi
  • 2,917
  • 22
  • 40
0

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

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

Bazidoa
  • 44
  • 5