Sharing Data Between Angular Components

In this article we discuss on how to Communicate (Data Passing) from two component.

1) Parent to Child Sharing data using Input decorator.


It’s most useful method for passing Data to parent component to child component using @Input() decorator. It allow pass data via the template.


Below is the basic example for passing data parent to child component.
Parent Component Code.


import { Component } from '@angular/core';
@Component({
  selector: 'parent-message',
  templateUrl: './parent.html'
})
export class AppComponent  {
  name = 'Angular'; 
}


<child-component name="{{ name }}"glt;</child-component>


Child Component Code.


import { Component, Input } from '@angular/core';

@Component({
  selector: 'child-component',
  template: `<h1>Parent Message:  {{name}}</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})

export class ChildComponent  {
  @Input() name: string;
}


Below is embedded code of the passing data from parent to child.

2) Child to Parent Sharing Data using Output() decorator and EventEmitter.


It mainly used when child sending data for parent component. For example when you click on the button of the chlid component we send message to parent component at that time we use these method.
In this method we need to create function in parent for geMessage.


In Child component we need to create function sendMessage which emit the event when trigger to send message from the child.
Below is the full example for how to communicate with Child to parent component.
Parent Component Code.


import { Component } from '@angular/core';
@Component({
  selector: 'parent-message',
  templateUrl: './parent.html'
})
export class AppComponent  {
  name = 'Angular'; 
  message:string='';
  receiveMessage($event) {
    this.message = $event;
  }

}


{{message}}
<child-component name="{{ name }}" (messageEvent)="receiveMessage($event)" glt;</child-component>


Child Component Code.


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

@Component({
  selector: 'child-component',
  template: `<h1>Hello {{name}}</h1>  <button (click)="sendMessage()">Send Message</button>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {
  @Input() name: string;

  message: string = "Receiving Message from child";
  @Output() messageEvent = new EventEmitter();

  sendMessage() {
    this.messageEvent.emit(this.message)
  }

}


Below is embedded code for passing data from child to parent.

Next article we discuss on how to send data using ViewChild & How to send data using Services to communicate between two different component.

Spread the love
  • 63
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •