How can I communicate between two child components in angular?

I am very new to angular 2. I have a problem for communication between two components. When I have a layout with a parent and some child components, it is easy to set child component variables with @Input annotation.

But now I have a layout for one parent component (mainly for the layout) and two child components:

layout example

Child component 2 has a bunch of buttons that creates only a simple message. Now I want to display this message in a child component.

How do I solve it? thanks in advance

+13
source share
4 answers

You can use @ViewChild and @Output to update properties in a child component.

Alternatively, you can use @Input instead of @ViewChild .

The approach suggested by seidme will also work just fine. It only depends on your use case.

Example of using @ViewChild and @Output : https://plnkr.co/edit/r4KjoxLCFqkGzE1OkaQc?p=preview

Example of using @Input and @Output https://plnkr.co/edit/01iRyNSvOnOG1T03xUME?p=preview

+8
source

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); // => Hello from child 1! }); } } 

See also this post: Angular2 - Interaction between components using a service

+15
source

A simple way is to set the output with @Output in child2 as an event and send the event with a message sent as its data when the button is clicked. Then listen to this event in your parent component and update the property that is set as the input of your child component1 when the event occurs.

Below is an image that clearly shows the mechanism

Component-IO

+10
source

You can use template variables to refer to siblings:

 <child1 #child1></child1> <child2 (someOutput)="child1.doSomething($event)"></child2> 
+9
source

Source: https://habr.com/ru/post/1014585/


All Articles