How can I communicate between two child components in angular? [duplicate]

Beside the solutions using the @Input/@Output and a parent component as a ‘bridge’, a common way would also be introducing a shared service. The service needs to be provided in a parent component so the children can share single instance of the service (How do I create a singleton service in Angular 2?).

Basic example using the 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) { }

    ngOnInit(): void {
        this.sharedService.messageSource.subscribe((message) => {
            console.log('Message: ', message); // => Hello from child 1!
        });
    }
}

See also: Angular2 – Interaction between components using a service

Leave a Comment