Angular Data Sharing Between Components

By | | Updated : 2022-04-27 | Viewed : 9041 times

Angular Passing Data Between Components

In the Real-time of Angular development, we may come across the situation where we need to pass data between the components. Here, I tried to write a sample tutorial with simple examples to understand the concept of data sharing between components in an angular application.

Parent To Child With @Input

For suppose you want to pass the data from the parent class to the child class, then you can use the @Input decorator. @Input decoration allows data sharing from the parent component to the child component. In our example that we are going to implement, we have a vendorName in VenderComponent to be required to pass into the child component ProductComponent.

Create Data Sharing Components Angular App

Let’s start the example to illustrate the data sharing from parent to child components in the angular application. Create an angular application using the below commands.

Commands To Create Angular Application
ng new Data-Sharing-Components-Angular-App

We will create now product and vendor components to implement the example for sharing the data from parent to child using @Input.

Create The Component Using Below Commands

Command To Create Components In Angular
ng g component input/Vender
ng g component input/Product

Write Code For Vendor Component And HTML

vender.component.ts
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-vender',
  templateUrl: './vender.component.html',
  styleUrls: ['./vender.component.css']
})
export class VenderComponent implements OnInit {

  vendorName = "Google";

  constructor() { }

  ngOnInit(): void {
  }

}
vender.component.html
<app-products [productVendor]="vendorName"></app-products>

Write Code For Product Component And HTML

product.component.ts
import { Component, Input, OnInit } from '@angular/core';

@Component({
  selector: 'app-product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {

  @Input() productVendor: string;
  
  constructor() { 
    this.productVendor = "";    
  }

  ngOnInit(): void {
  }

}
product.component.html
 <h2>Angular is maintaied by <span style="color:#00fff3;">{{ productVendor }}<span><h2>

Code Explanation

Now, we will try to understand how does data passed from parent to child.

vender.component.ts
vendorName = "Google";

Here, in VenderComponent, vendorName property is getting used in the venders.component.html as below.

vender.component.html
[productVendor]="vendorName"
product.component.ts
@Input() productVendor: string;

Here, in products.component.ts, @Input() decorator will fetch value and get assigned property to productVendor. The same property is getting used and displayed through products.component.html.

product.component.html
{{ productVendor }}

Child To Parent With @Output & @EventEmitter

Now, we need to understand about @Output and the EventEmitter.

We try to understand the @Output and EventEmitter. @Output, is a component decorator, allows data flow from child to parent. So when you need to pass data from child to parent then we can use @Output decorator. @Output should get initialized with EventEmitter. The definition of @Output contains EventEmitter.

Synatx for @Output
@Output() messageEvent = new EventEmitter<string>();

Create the few more component using below given cli commands.

Commands to create Components
ng g component viewchild/Vender
ng g component viewchild/Product

Write Code For Vendor Component And HTML

vender.component.ts
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-venders',
  templateUrl: './venders.component.html',
  styleUrls: ['./venders.component.css']
})
export class VendersComponent implements OnInit {

  constructor() { }
  ngOnInit() { }
  vendorName:string;

  receiveVendorName($event) {
    this.vendorName = $event
  }

}
vender.component.html
<div>
	<div style="bolder:red solid 1px;float:left;"><h1>Angular2 is maintained by: <span style="color:#00fff3;">{{vendorName}}</span></h1>
		<app-products (messageEvent)="receiveVendorName($event)"></app-products>
	</div>
</div>

Write Code For Component and Product HTML

product.component.ts
import { Component, OnInit, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.css']
})
export class ProductsComponent implements OnInit {

  constructor() { }

  ngOnInit() { }
  productVendor: string = "Google Inc";

  @Output() messageEvent = new EventEmitter<string>();

  ShowVendor() {
    this.messageEvent.emit(this.productVendor)
  }

}

Please see below given html for Vendors component and products.component.

product.component.html
<div style="bolder:red solid 1px;clear: left; ">
	<button (click)="ShowVendor()" style="color: black;background-color: #00fff3;font-size: 16px;border-radius: 4px 4px 4px 4px;">Show Vendor</button>
</div>

Execution flow:

  • In execution of app.component.html the tag will be interpreted. So Angular will create instance for component vendors.component.

  • In the VendersComponent, receiveVendorName() method will revcieve the event proerpty.

  • After encountering the tag in the venders.component.html, the ProductsComponent will be initialized. In the component ProductsComponent, messageEvent is an @Output() decarator. When we click the button showVendor, event will be triggered. By using @Output(), the property can be exposed to the other component VendersComponent

  • The exposed value will be bind by the parent component VendersComponent and will be populated the same in the UI client browser.

Child To Parent With @ViewChild

To pass one component's data into another component we can use the @ViewChild decorator. Please see the below given example that will show how to send Products data into Vendors component.

vendor.component.ts
import { Component, AfterViewInit, ViewChild } from '@angular/core';
import { ProductsComponent } from '../products/products.component';


@Component({
  selector: 'app-vendors',
  templateUrl: './vendors.component.html',
  styleUrls: ['./vendors.component.css']
})
export class VendorsComponent implements AfterViewInit {

  constructor() { }
  
  vendorName:string;
  
  @ViewChild(ProductsComponent)
  private productsComponent: ProductsComponent;
  
  ngOnInit() {
	this.vendorName =  this.productsComponent.productVendor
  }
  /*ngAfterViewInit() {
    this.vendorName =  this.productsComponent.productVendor
  }*/

}
vendor.component.html
<h2>Angular is maintaied by <span style="color:#00fff3;">{{ vendorName }}<span><h2>
<app-products></app-products>
product.component.ts
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.css']
})
export class ProductsComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }
  productVendor='Google';

}

Execution flow:

  • The Angular will create the instance for component vendors.component when encounter the tag in index.html.

  • VendorsComponent has @Viewchild will be used to inject child component into parent component i.e., VendorsComponent.

  • After loading the parent component view VendorsComponent view then @ViewChild will enable VendorsComponent to fetch the child component data i.e., ProductsComponent.

  • If you observe the productVendor variable will be passed form child component ProductsComponent to parent component VendorsComponent.

We will discuss the about the Sharing data using with services in the later chapters.

Leave A Reply