Communication Between Components Using @Input() in Angular

Dhananjay Kumar / Tuesday, December 13, 2016

In Angular, a component can share data and information with another component by passing data or events. A component can be used inside another component, thus creating a component hierarchy. The component being used inside another component is known as the child component and the enclosing component is known as the parent component.  Components can communicate to each other in various ways, including:

  1. Using @Input()
  2. Using @Output()
  3. Using Services
  4. Parent component calling ViewChild
  5. Parent interacting with a child using a local variable

In this article, we will focus on how a child component can interact with a parent component using the @Input() property. We’ll also look into intercepting the input message and logging changes in the input message.

 

Let us consider the components created in the listing below. We have created a component called AppChildComponent, which will be used inside another component.

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

@Component({
    selector: 'appchild',
    template: `<h2>Hi {{greetMessage}}</h2>`
})
export class AppChildComponent {

        greetMessage: string = "I am Child";

    }

We have also created another component called AppComponent. Inside AppComponent, we are using AppChildComponent:

import {Component } from '@angular/core';
import {AppChildComponent} from './appchild.component';

@Component({
    selector: 'my-app',
    template: `<h1>Hello {{message}}</h1> <br/> 
  <appchild></appchild>
  `,
})
export class AppComponent  { 
  
        message : string = "I am Parent";

    }

In the above listings, AppComonent is using AppChildComponent, hence AppComponent is the parent component and AppChildComponent is the child component.

 

Passing data from parent component to child component

Let us start with passing data from the parent component to the child component. This can be done using the input property. @Input decorator or input properties are used to pass data from parent to child component. To do this, we’ll need to modify child AppChildComponent as shown in the listing below:

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

@Component({
    selector: 'appchild',
    template: `<h2>Hi {{greetMessage}}</h2>`
})
export class AppChildComponent  implements OnInit{

    @Input() greetMessage: string ;
        constructor(){

        }   
        ngOnInit(){

        }
    }

As you notice, we have modified the greetMessage property with the @Input() decorator. Also, we have implemented onInit, which will be used in demos later.  So essentially, in the child component, we have decorated the greetMessage property with the @Input() decorator so that value of the greetMessage property can be set from the parent component.

Next, let us modify the parent component AppComponent to pass data to the child component.

import {Component } from '@angular/core';
import {AppChildComponent} from './appchild.component';

@Component({
    selector: 'my-app',
    template: `<h1>Hello {{message}}</h1> <br/> 
  <appchild [greetMessage]="childmessage"></appchild>
  `,
})
export class AppComponent  { 
  
        message : string = "I am Parent";
        childmessage : string = "I am passed from Parent to child component"

    }

From the parent component, we are setting the value of the child component’s property greetMessage. To pass a value to the child component, we need to pass the child component property inside a square bracket and set its value to any property of parent component. We are passing the value of the childmessage property from the parent component to the greetMessage property of the child component.

Intercept input from parent component in the child component

We may have a requirement to intercept data passed from the parent component inside the child component. This can be done using getter and setter on the input property.

Let us say we wish to intercept an incoming message in the child component, and combine it with some string.  To achieve this, we created a property called _greetmessage and using @Input() decorator creating getter and setter for the _greetmessage property. In the getter, we’re intercepting the input from the parent component and combining it with the string. This can be done as shown in the next listing:

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

@Component({
    selector: 'appchild',
    template: `<h2>Hi {{_greetMessage}}</h2>`
})
export class AppChildComponent  implements OnInit{


        _greetMessage : string; 
        constructor(){

        }   
        ngOnInit(){

        }

    @Input()
        set greetMessage(message : string ){
            this._greetMessage = message+ " manipulated at child component"; 
        }
        get greetmessage(){
            return this._greetMessage;
        }

    }

In the setter, we are manipulating incoming data from the parent component and appending some text to that. Keep in mind that the behavior of the parent component would not change whether we are intercepting the message or not. To explore it further, let us take another example and create a child component, which will display names passed from the parent. If the parent passes empty name value, then the child component will display some default name. To do this, we have modified the setter in the child component. In the setter, we are checking whether the name value is passed or not. If it is not passed or it is an empty string, the value of name would be assigned to a default value. The child component can be created as shown in the listing below:

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

@Component({
    selector: 'appchild',
    template: `<h2>{{_name}}</h2>`
})
export class AppChildComponent  implements OnInit{


        _name: string; 
        constructor(){

        }   
        ngOnInit(){

        }

    @Input()
        set Name(name : string ){
            this._name = (name && name.trim()) || "I am default name"; 
        }
        get Name(){
            return this._name;
        }

    }

As you notice in the @Input() setter, we are intercepting the value passed from the parent, and checking whether it is an empty string. If it is an empty string, we are assigning the default value for the name in the child component.

We can use AppChildComponent inside parent component AppComponent as shown in the listing below:

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

@Component({
    selector: 'my-app',
    template: `<h1>Hello {{message}}</h1> <br/> 
  
    <appchild *ngFor="let n of childNameArray" 
    [Name]="n">
    </appchild>
  `,
})
export class AppComponent  { 
  
        message : string = "I am Parent";
        childmessage : string = "I am passed from Parent to child component"
        childNameArray = ['foo','koo',' ','moo','too','hoo',''];

    }

Inside parent component, we are looping the child component through all items of childNameArray property. A few items of the childNameArray are empty strings, these empty strings would be intercepted by the child component setter and set to the default value. The child component will render the values passed from the parent component as shown in the image below:

ngOnChanges and @Input() decorator

We can intercept any input property changes with OnChanges lifecycle hook of the component. There could be various reasons that Input property can be changed in the parent component and needed to be intercepted in the child component. This can be done on the OnChanges lifecycle hook.

Let’s imagine we need to log changes in an Input variable called counter. The value of the counter is set by the parent component and can be changed in the parent component. Whenever the value of the counter is changing in the parent component, we need to log the changes in the child component. We created a child component as shown in listing below:

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

@Component({
    selector: 'appchild',
    template: `<h2>{{counter}}</h2>
    <h2>Value  Changed</h2>
    <ul>
    <li *ngFor="let c of changeLog">{{c}}</li>
    </ul> 
    `
})
export class AppChildComponent  implements OnChanges{

    @Input() counter = 0 ; 
        changeLog : string[] = []; 
        constructor(){

        }   

    
        ngOnChanges(changes : {[propKey:string]: SimpleChange}){

        let  log : string [] =[];
        for(let p in changes){
            let c = changes[p];
            console.log(c);
            let from = JSON.stringify(c.previousValue);
            let to = JSON.stringify(c.currentValue);
            log.push(`${p} changed from ${from} to ${to}`);

        }

        this.changeLog.push(log.join(', '));

    }

    }

Essentially we are doing the following:

  1. Implementing OnChanges lifecycle hook
  2. In the ngOnChanges method, passing an array of type SimpleChange
  3. Iterating through all the changes and pushing it to a string array

Whenever the value of counter will be changed, the child component will log the previous value and current value. The reading of the previous value and current value for each input properties is done in the ngOnChnages method as shown in the image below.   

At the parent component, we are assigning a new random number to count the property on click of the button, and also setting the count property as the value of the child component’s input property counter.

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

@Component({
    selector: 'my-app',
    template: `<h1>Hello {{message}}</h1> <br/> 
   <button (click)="nextCount()">change count</button> <br/>
   <appchild [counter]="count"></appchild> 
  `,
})
export class AppComponent  { 
  
        count : number = 0; 

        nextCount(){
            console.log("hahahah");
            this.count = this.getRandomIntInclusive(this.count,this.count+1000);
        }

        getRandomIntInclusive(min :number, max: number) {
            min = Math.ceil(min);
            max = Math.floor(max);
            return Math.floor(Math.random() * (max - min + 1)) + min;
        }

    }

Essentially in the parent component, we are setting the value of the child component’s input property counter with the parent component’s count property, and also changing its value on each click of the button.  Whenever the count property value changes at the parent component, the value of the counter input property will be changed in the child component and the changed value would be logged.

On running the application, we may get the expected output with a change log as shown in the image below:

Conclusion

In this article, we learned how to pass data from a parent component to a child component. We also learned how to intercept the input message and log changes. In further posts, we will explore more aspects of component communication. I hope you found this post useful, thanks for reading!