Sharing data between components in Angular

Sharing data between components in Angular it’s easy and there are some steps you need to know:

1. Parent to Child using @Input() decorator
2. Child to Parent using @Output decorator via event Emitter
3. Using a shared service

Before diving into those sections let’s start by describing some important aspects that you need to know about Angular.

What is data binding ?

Data binding it’s a process of connecting a view to the business logic, in our case the view is an angular component and the business logic is the data that we want to show. Sharing data in angular from parent to child is made by usage of @Input decorator.

@Input and @Output act as a endpoint, @Input is for letting the data to flow in while @Output is letting the data to flow out. In fact if you think that your component is a “house”, the “house” has the front door witch in our case is the @Input decorator and the back door is the @Output decorator.

In most cases we don’t need to use both decorators, and to cover our first point from the article to share the data from parent to child we need to use @Input decorator, let’s see an example:

<div style="text-align:center; background: green; min-height: 300px">
	<h1 style="color: #fff">
         {{ parentMessage }}
	</h1>
  <app-child [item]="message"></app-child>
</div>

This is the HTML template for the parent component in witch we can see the tag for the child component, the child has some data binding on it, message being the value taken from the parent.

Sharing data using @Input decorator
Sharing data using @Input decorator

Event Emitter in Angular

To use @Output we need to create an instance of the Event Emitter, every time you need to do an action (click, form submission) you need to use the Event Emitter to send the action to the parent. In our case we use it with @Output decorator in order to send the values back to parent component.

import { Component, Input, Output, EventEmitter } from "@angular/core";

@Component({
  selector: "app-child",
  templateUrl: "./child-app.component.html",
  styleUrls: ["./child-app.component.css"]
})
export class ChildAppComponent {
  @Input() item: string;
  @Output() childMessageEvent = new EventEmitter<string>();
  childMessage: string = "Child message!";

  sendMessage() {
    this.childMessageEvent.emit(this.childMessage);
  }
}

As we can see we declared our event on line 2 and we created a function “sendMessage” witch is emitting a value from child to parent. On parent html template we should have:

<div style="text-align:center; background: green;">
  <h1 style="color: #fff">
    {{ parentMessage }}
  </h1>
  <app-child [item]="message" (childMessageEvent)="receiveMessage($event)">
  </app-child>
  <p>Message from child: {{childMessage}}</p>
</div>

Shared service

A shared service is an outside component witch is isolated and can be injected in any component. In angular we have dependency injection pattern, we define our service with @Injectable decorator and we create some methods for it. To use the service we simply inject the service in the constructor component:

constructor(private sharedService: SharedService) {}

Our next step is to have a shared service witch can help us to share data between components:

import { Injectable } from "@angular/core";
import { BehaviorSubject } from "rxjs";

@Injectable()
export class SharedService {
 private msgRoot = new BehaviorSubject<string>("default message");
 currentMsg = this.msgRoot.asObservable();

 changeMessage(message: string) {
   this.msgRoot.next(message);
 }
}

We defined “msgRoot” as a BehaviorSubject, witch is a helper from “rxjs” library, and if you like to learn more check their docs , then we define other variable witch is getting the “msgRoot” value as an observable.
Observable’s is other important topic and if you don’t know how they works you can access this link .

So we discussed about dependency injection and a shared service in witch we need to define a method to change our value from message variable.

As we saw before we have some rules to share data in Angular, parent to child, child to parent and using a shared service.
You can see the full code here , also you can read a nice article about angular animations here . Enjoy!

Sharing is caring!


Leave a Reply

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