Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Share a method between two child components (Angular)

There is such structure of components:

enter image description here

Desired Behavior

child1_component - is a header.

child2_component - is a body.

There is a button inside child1_component.

Clicking on that button I want to invoke a method inside child2_component.

Question

What is the best way to implement this?

like image 905
Ivan Burzakovskiy Avatar asked Nov 24 '25 10:11

Ivan Burzakovskiy


1 Answers

One way to approach this would be to use a service with rxjs subjects and observables.

  1. When the user clicks on the button in child1_component then it calls a method that in turn calls a method inside the shared service.

  2. When the method in the service is called it can emit a value as an observable via a subject.

  3. child2_component then subscribes to the observable within the shared service and can operate some logic based on when it receives data from the service.

More on services here: https://angular.io/tutorial/toh-pt4

Great tutorial on subjects and rxjs: https://blog.angulartraining.com/rxjs-subjects-a-tutorial-4dcce0e9637f

like image 105
CaeSea Avatar answered Nov 26 '25 22:11

CaeSea



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!