How to Pass data Between Components in Angular

How we can pass data from one component to another component?

We can also pass the data from one component even if parent and child relationships exists or not between them. If the components are separate and we want to pass data than we can use services using get and set properties. Set property is used for setting the values which you want
and get for getting the values which is added by a component.

Angular Login and Signup using JSON-Server | Angular Routing | Angular Reactive Form

pass data from parent component to child component using @Input.

According to the above image, it is very easy to pass data from Parent to Child, you need to remember the following steps,

At the parent side, Declare a variable and use it as a Property Binding and assign a value, when parent component is called, like .

In the child component, fetch this variable in component (.ts file) using the @Input decorator function, like @Input () variable name: type of variable

The use it into child HTML page.

What is Bootstrapping in Angular & how to use it?

pass data from child component to parent component using @Output.

According to the image above, it is simple to pass data from Child to Parent component, you need to remember the following steps.

On Child component

Go to the HTML page, use event binding and call a function to set the value.

Go to the component page which means .ts and declare a property with @Output(), like @Output () variable name=new EventEmitter();

And emit data using this variable like this.variablename.emit(passing-data) On Parent component

Go to the HTML page, use the same variable name as defined in the child component with @Output( ), as an event binding Go to the component page and inside the method set the value and use it in the parent HTML.

What is Event Emitter?

As components is used in Angular and there are many events that we are using so, component emits the event using @output and event emitter. When we pass the value from child to parent component, parent can emit the value anytime using event emitter. Basically, directives are used to extend the power of HTML attributes and to model and reshape the DOM structures

Leave a Reply

Your email address will not be published. Required fields are marked *