JohnV
JohnV

Reputation: 31

Angular2 Child-Child Communication

How do you perform Child-Child communicationin Angular2? The Angular2 Documentation Describes many ways of performing Parent-Child communication. However, How can children contained by a parent interact with each other? Can one child capture an even emitted by another? So far my attempts have failed, and I would like to know if anyone has a good pattern for Child-Child communication.

For instance, how can I wire these two child components to hear events emitted by each other? This is my attempt so far:

@Component({
  template: `
    <section>          
      <app-countdown-timer (onResetTimer)="countdownTimerComponent.resetCountDownTimer()"></app-countown-timer>        
      <app-buildplan (onTimedOut)="buildPlan.perfomTimeOutAction()"></app-buildplan>
    </section>
`,
...
})
export class CreateBuildplanComponent implements OnInit {
  @ViewChild(BuildPlanComponent) private buildPlan: BuildPlanComponent;
  @ViewChild(CountdownTimerComponent) private countdownTimerComponent:CountdownTimerComponent;
...
}

Upvotes: 1

Views: 322

Answers (2)

JohnV
JohnV

Reputation: 31

I figured this out, at least for Child-Child communication through events. It turns out that the onTimedOut event emitted by the app-countdown-timer needs to be listend to in it's own selector, ie <app-countdown-timer (onTimedOut)="..">. The same goes for the the other components. The @ViewChild(BuildPlanComponent) private buildPlan: BuildPlanComponent; in the parent class allows access to the "builplan" component in the parent template (ie (onTimedOut)="buildPlan.perfomTimeOutAction()")

@Component({
  template: `
    <section>          
      <app-countdown-timer (onTimedOut)="buildPlan.perfomTimeOutAction()"></app-countown-timer>        
      <app-buildplan (onResetTimer)="countdownTimerComponent.resetCountDownTimer()"></app-buildplan>
    </section>
`,
...
})
export class CreateBuildplanComponent implements OnInit {
  @ViewChild(BuildPlanComponent) private buildPlan: BuildPlanComponent;
  @ViewChild(CountdownTimerComponent) private countdownTimerComponent:CountdownTimerComponent;
...
} 

Upvotes: 0

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657486

You can use template variables like

  <app-countdown-timer #countdown 
    (onResetTimer)="buildplan.resetCountDownTimer()"></app-countown-timer>        
  <app-buildplan #buildplan 
    (onTimedOut)="countdown.perfomTimeOutAction()"></app-buildplan>

This example calls an event handler from the sibling. Not sure if this is exactly what you tried to do.

Upvotes: 1

Related Questions