13

I have 2 sibling components that need to communicate:

<app-controls></app-controls> <app-main></app-main>

app-controls contains buttons that need to trigger events in the app-main component. Is there a Angular 2 style guide compliant way of doing so?

wesley.ireland
  • 643
  • 3
  • 12
  • 21

2 Answers2

28

You can use a template variable to get a reference to the sibling. If <app-controls> has an output where it emits events when a button is clicked you can do:

<app-controls (buttonClicked)="main.doSomething($event)"></app-controls>
<app-main #main></app-main>

or you can pass a reference to a @Input() siblings; and then call methods on it:

<app-controls [sibling]="main"></app-controls>
<app-main #main></app-main>
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
4

Two ways:

Use a shared Service with dependency injection.

Or using the @Input() und @Output() decorators:

https://angular.io/docs/ts/latest/cookbook/component-communication.html

slaesh
  • 16,659
  • 6
  • 50
  • 52