How to Pass Data Between Components in Angular 2

Muhammad Adil Feb 02, 2024
  1. Use Input Decorator to Pass Data From Parent to Child Components in Angular 2
  2. Use the Output and EventEmitter to Pass Data From Child to Parent Components in Angular 2
  3. Use Service to Pass Data Between Components in Angular 2
How to Pass Data Between Components in Angular 2

This article will show you how to pass data between two components in Angular 2.

Use Input Decorator to Pass Data From Parent to Child Components in Angular 2

Parent to Child via Input() decorator is used when a parent component needs to communicate with its child component. The parent component sends data or performs actions on the child component.

It works by providing data through the template using the @Input() decorator. This is used to modify and track the component’s input settings.

The following code examples will demonstrate how to create this type of relationship between two components using the input decorator in Angular 2.

TypeScript code (App.component.ts):

import { Component } from '@angular/core';
import { Demo } from './Demo';
@Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
    DemoEx:Demo[] = [
        new Demo('First Example'),
        new Demo('SECOND Example')
    ];
}

TypeScript code (input.component.ts):

import { Component, OnInit, Input} from '@angular/core';
import { Demo } from '../Demo';
@Component({
    selector: 'app-demo',
    templateUrl: './input.component.html',
    styleUrls: ['./input.component.css']
})
export class inputCom implements OnInit {
    @Input() Demo: Demo;
    constructor() { }
    ngOnInit() {
    }
}

HTML code (app.component.html and input.component.html):

<main>
<section>
    <div class="card">
        <header>{{Demo.name}}</header>  
    </div>
</section>
</main>
<h3>Parent to child Component Interaction in Angular</h3>
<app-demo *ngFor="let Demo of DemoEx" [Demo]="Demo"></app-demo>

Click here to check the live demonstration of the code above.

Use the Output and EventEmitter to Pass Data From Child to Parent Components in Angular 2

EventEmitter is a class that can emit custom events. It is an Angular 2 component that enables you to use the observable pattern in Angular 2 applications.

This component offers an alternative to the traditional callback pattern and simplifies the process of triggering change detection by unsubscribing from observables when they are no longer needed.

The following example shows how the parent component subscribes to the event and changes its behavior accordingly.

TypeScript code (parent.component.ts):

import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
    selector: 'parent',
    template: '<button (click)="DemoEx()">Click here to go to the next component</button>',
})
export class ParentComponent  {
    @Input() name: string;
    @Output() SampleEx = new EventEmitter<string>();
    DemoEx() {
        this.SampleEx.emit(this.message)
    }
    message: string = "You are in Child Component";
}

TypeScript code (app.component.ts):

import { Component } from '@angular/core';
@Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
    name = 'Angular';
    message:string='';
    NextCom($event) {
        this.message = $event;
    }
}

HTML code (app.component.html):

<parent name="{{ name }}" (SampleEx)="NextCom($event)"></parent>
<br/>
<br/>
{{message}}

Click here to check the live demonstration of the example above.

Use Service to Pass Data Between Components in Angular 2

A service is a class that implements the Injectable interface. It has to have methods annotated with Injectable Decorator and implement one or more interfaces if needed.

A shared service should be used when transmitting data across components that do not have a direct link. When data needs to be in sync all of the time, the RxJS BehaviorSubject comes in handy.

We can set the name as an observable that can be modified using the.next() method using BehaviorSubject. Then we can extract the last value as raw data using the getValue() function.

The current value is saved in BehaviorSubject. As a result, the component will always read the most recent data value in BehaviorSubject.

See the example below.

TypeScript code (first.component.ts):

import { Component, OnInit } from '@angular/core';
import { SharedService } from '../demo.service';
@Component({
    selector: 'app-demo1',
    templateUrl: './first.component.html',
    styleUrls: ['./first.component.css']
})
export class FirstComponent implements OnInit {
    sharedData: string;
data: any;
    constructor(private sharedService: SharedService) { }
    ngOnInit() {
        this.sharedService.sharedData$
        .subscribe(sharedData => this.sharedData = sharedData);
    }
    updateData() {
        this.sharedService.setData(this.data);
    }
}

TypeScript code (second.component.ts):

import { Component, OnInit } from '@angular/core';
import { SharedService } from '../demo.service';
@Component({
    selector: 'app-demo',
    templateUrl: './second.component.html',
    styleUrls: ['./second.component.css']
})
export class SecondComponent implements OnInit {
    sharedData: string;
data: any;
    constructor(private sharedService: SharedService) { }
    ngOnInit() {
        this.sharedService.sharedData$
        .subscribe(sharedData => this.sharedData = sharedData);
    }
    updateData() {
        this.sharedService.setData(this.data);
    }
}

HTML code:

<h3>2nd Component</h3>
<input type="text" [(ngModel)]="data">
<button (click)="updateData()">Save</button>
<br>
<br>
Saved Data {{ sharedData }}
<h1>Example of Unrelated Components: Sharing Data with a Service</h1>
<h3>1st Component</h3>
<input type="text" [(ngModel)]="data">
<button (click)="updateData()">Save</button>
<br>
<br>
SavedData {{ sharedData }}

The benefit of passing data between components is that you can better comprehend your project by breaking it down into smaller parts, allowing you to focus without being burdened by the hundreds of code lines.

A team can also operate more productively if each developer works on separate components.

Click here to check the live demonstration of the example above.

Muhammad Adil avatar Muhammad Adil avatar

Muhammad Adil is a seasoned programmer and writer who has experience in various fields. He has been programming for over 5 years and have always loved the thrill of solving complex problems. He has skilled in PHP, Python, C++, Java, JavaScript, Ruby on Rails, AngularJS, ReactJS, HTML5 and CSS3. He enjoys putting his experience and knowledge into words.

Facebook

Related Article - Angular Component