How Angular components communicate?

Shashank J Patel

Apr 07, 2020 | 4 min read

How Angular components communicate

What are components in Angular?

Components are the basic building blocks of Angular applications.

In a simpler manner, we can say components are UI/ View elements along with the mechanism to show and operate on data.

The Angular Team defines a component as the Patch of the screen that we call a View which declares the reusable building blocks for an application.

So, A component is anything which is visible on the screen, which can be reused again and again.

#Prerequisites

  • Node installed on your machine
  • NPM installed on your machine
  • Basic Knowledge of JavaScript
  • Installing Angular CLI 8 : npm install -g @angular/cli
  • Creating your Angular 8 Project : ng new angular-example
  • Creating Components : ng g c payment-components
  • Run on local Server on http://localhost:4200 : ng serve

3 ways to communicate data between Angular components

  • Parent to Child: Sharing Data via Input
  • Child to Parent: Sharing Data via ViewChild with AfterViewInit
  • Child to Parent: Sharing Data via Output() and EventEmitter

1. Parent to Child: Sharing Data via Input

To share data from parent to child component via @Input Decorator.

@Input links a property of a child component with a value that was given by the parent component.

For e.g :

Create 2 components parent.component.ts and child.component.ts

Let's create a simple string variable in our parent.component.ts file, It will contain the message that we want to give to our child.

Add bellow code in parent.component.ts file :

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

@Component({
  selector: 'app-parent',
  template: ` 
     <app-child [childMessage]="parentMessage"></app-child> 
`,
  styleUrls: ['./parent.component.css']
})

export class ParentComponent{
    
  parentMessage = "message from parent";

  constructor() { }
}
parent.component.ts

Add bellow code in child.component.ts file :

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

@Component({
  selector: 'app-child',
  template: ` Say {{ message }  `,
  styleUrls: ['./child.component.css']
})

export class ChildComponent {
    
  @Input() childMessage: string;

  constructor() { }
}

child.component.ts

2. Child to Parent: Sharing Data via ViewChild with AfterViewInit

ViewChild allows a child component to be injected into a parent component.

It will give the parent access to its attributes and functions.

A Child won’t be available to give access until the view has been initialized.

This means we need to implement the AfterViewInit lifecycle hook to receive the data from the child.

Add bellow code in parent.component.ts file :

import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from "../child/child.component";

@Component({
  selector: 'app-parent',
  template: `
    Message: {{ message }}
    <app-child></app-child>
  `,
  styleUrls: ['./parent.component.css']
})

export class ParentComponent implements AfterViewInit {
  
  @ViewChild(ChildComponent) child;
  
  constructor() { }
  
  Message:string;
  
  ngAfterViewInit() {
    this.message = this.child.message
  }
}
parent.component.ts

Add bellow code in child.component.ts

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

@Component({
  selector: 'app-child',
  template: `  `,
  styleUrls: ['./child.component.css']
})

export class ChildComponent {
    
  message = 'Hello Angular!';

  constructor() { }

}
child.component.ts

3. Child to Parent: Sharing Data via Output() and EventEmitter

Another way to share data is to emit data from the child component which can be listed by the parent component.

This approach is ideal when you want to share data changes that occur on things like button clicks, form entries, and other user events.

For e.g.

In the parent, we create a function to receive the message and set it equal to the message variable.

In the child, we declare a messageEvent variable with the Output decorator and set it equal to a new event emitter.

Then we create a function named sendMessage that calls emit on this event with the message we want to send. Lastly, we create a button to trigger this function.

The parent can now subscribe to this messageEvent that’s outputted by the child component, then run the receive message function whenever this event occurs.

Add bellow code in parent.component.ts file :

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

@Component({
  selector: 'app-parent',
  template: `
    Message: {{message}}
    <app-child (messageEvent)="receiveMessage($event)"></app-child>
  `,
  styleUrls: ['./parent.component.css']
})

export class ParentComponent {
    
    constructor() { }
    
    Message:string;

    receiveMessage($event) {  
        this.message = $event  
    }
}

parent.component.ts

Add bellow code in child.component.ts file :

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

@Component({
  selector: 'app-child',
  template: `
      <button (click)="sendMessage()">Send Message</button>
  `,
  styleUrls: ['./child.component.css']
})

export class ChildComponent {
    
  message: string = "Hey Angular!"

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

  constructor() { }

  sendMessage() {
    this.messageEvent.emit(this.message)
  }
}
child.component.ts

#Conclusion

  • Here we define how to share data between component in Angular 8
  • We can share data from parent to child via @Input
  • We can share data from child to parent via ViewChild
  • We can share data from child to parent via @Output for button clicks or Form entries

Third Rock Techkno is a leading IT services company. We are a top-ranked web, voice and mobile app development company with over 10 years of experience. Client success forms the core of our value system.

We have expertise in the latest technologies including angular, react native, iOs, Android and more. Third Rock Techkno has developed smart, scalable and innovative solutions for clients across a host of industries.

Our team of dedicated developers combine their knowledge and skills to develop and deliver web and mobile apps that boost business and increase output for our clients.