• Rahul Prabhune

Sharing Data Between Components

Updated: Dec 20, 2017

In this post, we will learn 3 ways of sharing data between different components.

So let's start by creating a project called data-sharing

ng new data-sharing

now create two component child and parent

ng g c components/child
ng g c components/parent

These command will create two components in components directory. (If you don’t have 'components' directory, it will create one)

Now create a service using command

ng g s services/data

This will create a service in ‘services’ directory. After creating data service don’t forget to add it in providers array in app.module.ts file.

Your app.module.ts file should look like this.

Now serve your application using

ng serve

Via Input()

Let assume at first child component have a field name and it don’t have any value. So from parent component we will send value of name to child component. For that we have to use @Input sign in front of name field.

So when calling child component, parent will also give a variable by which that component sends data to the child component.



Our Final output is

Via @Output() and EventEmitter

Now child wants to send a message to parent and it possible by @output and EventEmitter. First we will declare a variable in child component named ‘message’.

Then we have to create a EventEmitter type variable which will be decorated with @Output().

Then we have to create a function which will emit message.

Now in child.component.html file we will get a input field which will be binded with ‘message’ and a ‘Send Message’ button which click event will be connected with sendMessage().

In parent component, we will create a new variable called ‘message’ and a function to receive message from the function.

And in parent.component.html we have to bind this ‘receiveMessage($event)’ with @Output(‘message’) in child component.

Our final result is

Sending Data via Service

Now, the child wants pocket money from parent and child can tell his parent how much child wants also parent can tell child how much child will get as pocket money. We need a system where, when child change pocket money amount that will immediately show in parent also vice versa.

For this problem, we have to use a new class which will be connected to both child and parent. So our class is data.service.ts, here we will declare a pocketMoney object which has amount attribute.

Now we have to create same type object in child.component.ts and parent.component.ts. And initialize them in during that class initialization by implementing the OnInit interface. Now create an input field in child.component.html and bind that input field with pocketMoney.amount. Do same in parent.component.html.




Now final result is,