Angular Cross Component Communication

“Previously on Lost”

Image for post
Image for post

It is very common need to interact with the other component while developing any kind of frameworks or libraries. In angular there are ways to do it.

Image for post
Image for post
You can use property binding to communicate between parent and child components.

You generally use Input and Output decorators communication between parent and child components but if its about interaction between cross components that would be enough tough to use property binding usage. It is great way to use injectable services to transmit the data between cross components.

Image for post
Image for post

Services make codes leaner, easier to maintain it is not necessary to build with these complex input and output things where you passed the events and properties to communicate between components.

I’ve made a simple example which includes two components under app component. First component takes the input from user and the other one lists it via injected service. Here is my service file of a-component.

Image for post
Image for post
Emitting Lost TV Series characters array in my service file.

In my a-component file added two default character and user adds over it. When page rendered first i wanna see the default characters so i also emit the characters array in ngOnInit() method.

Image for post
Image for post
Image for post
Image for post
Here is my form to get user input.

When clicked on emits the user input in a.service file then to get data from b-component it needed to be subscribed with importing the a-component’s service.

Image for post
Image for post

So data which is transmitted from a-component ready to be used in the b-component. Simple :)

Image for post
Image for post
I don’t remember the job of her :)

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium