The global answer is to leverage a shared service and use it to communicate between components.
Most of the time, you need to define your shared service when bootstrapping your application:
bootstrap(AppComponent, [ SharedService ]);
and not defining it again within the providers
attribute of your components. This way you will have a single instance of the service for the whole application.
You can implement the shared service like that:
export class SharedService {
valueUpdated:Subject<any> = new Subject();
updateData(data:any) {
this.valueUpdated.next(data);
}
}
To be notified, simply subscribe to the subject
constructor(private service:SharedService) {
this.service.valueUpdated.subscribe(data => {
// do something
});
}
One component is a sub component of your AppComponent
one, simply remove the providers
attribute like this:
@Component({
selector : "other",
// providers : [SharedService], <----
template : `
I'm the other component. The shared data is: {{data}}
`,
})
export class OtherComponent implements OnInit{
(...)
}
This way they will shared the same instance of the service for both components. OtherComponent
will use the one from the parent component (AppComponent
).
This is because of the "hierarchical injectors" feature of Angular2. For more details, see this question:
By injecting the parent into the child, you need to be careful about cyclic dependency (use forwardRef
- see https://angular.io/docs/ts/latest/api/core/index/forwardRef-function.html). But it's possible to have something like that:
@Component({
template: `
<div (click)="onClick()">Click</div>
`,
(...)
})
export class CpTwo{
constructor(private cp : CpOne){}
onClick() {
this.cp.setValue({ value: 'some value' });
}
}