Angular Communication between components

Javascript
1 min readOct 13, 2020

There are 3 ways to communicate between angular components.

  1. Input and output decorator
  2. Using Services
  3. View Child Decorator.

Input and output decorator:

@Input Decorator

This is require to send data from parent to child component.

Steps:

import input library from @angular/core in child component

decorate the property with @Input() which needs to receive from parent component.

childComponent.ts

import {component,Input} from ‘@angular/core’;

export class ChildComponent{

@Input()

target:<String>;

}

childComponent.html

<p>{{target}}</p>

Bind the property in parents component’s template

use child selector as a decorator in parent component and use property binding to bind property with child component property.

parentComponent.ts

export class ParentComponent{

item:<String> =” ”;

}

parentComponent.html

<div class =”container”>

<app-child-component [target]=item></app-child-component>

</div>

@Output Decorator

Use @Output to send data from child to parent component.

Steps to use

import Output, EventEmitter from ‘@angular/core’ in child component.

create an event and decorate with @output() decorator.

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

raise an event emitter for sharing data to parent component.

export class childComponent{

@Output() exportItem = new EventEmittet<string>()

raiseEvent (){

this.exportItem.emit(“hai hello”)

}

}

Now attach an event binding in parent component to recieve element from child component.

ParentComponent.html

<parent-component>

<app-child-component (exportItem)=”addItem($event)”></app-child-component>

</parent-component>

--

--