Besides solutions using @Input
/ @Output
and the parent component as a "bridge", the general method will also represent the common service. The service must be provided in the parent component so that children can share the same service instance ( How do I create a single-user service in Angular 2? ).
Basic example using BehaviorSubject as a delegate :
@Injectable() export class SharedService { messageSource: BehaviorSubject<string> = new BehaviorSubject(''); constructor() { } }
Child component 1:
export class ChildComponent1 { constructor(private _sharedService: SharedService) { } sendMessage(): void { this._sharedService.messageSource.next('Hello from child 1!'); } }
Child component 2:
export class ChildComponent2 { constructor(private _sharedService: SharedService) { this._sharedService.messageSource.subscribe((message: string) => { console.log('Message: ', message);
See also this post: Angular2 - Interaction between components using a service
source share