DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

How does AI transform chaos engineering from an experiment into a critical capability? Learn how to effectively operationalize the chaos.

Data quality isn't just a technical issue: It impacts an organization's compliance, operational efficiency, and customer satisfaction.

Are you a front-end or full-stack developer frustrated by front-end distractions? Learn to move forward with tooling and clear boundaries.

Developer Experience: Demand to support engineering teams has risen, and there is a shift from traditional DevOps to workflow improvements.

Related

  • Angular Component Tree With Tables in the Leaves and a Flexible JPA Criteria Backend
  • Bing Maps With Angular in a Spring Boot Application
  • Comprehensive Guide to Property-Based Testing in Go: Principles and Implementation
  • Rediscovering Angular: Modern Advantages and Technical Stack

Trending

  • How to Install and Set Up Jenkins With Docker Compose
  • How to Use Testcontainers With ScyllaDB
  • Kung Fu Commands: Shifu Teaches Po the Command Pattern with Java Functional Interfaces
  • The Rise of Self‐Service Platforms: How Cloud Development Environments Are Reshaping Dev Culture
  1. DZone
  2. Coding
  3. Frameworks
  4. Communication Between Components Using @Input() in Angular 2

Communication Between Components Using @Input() in Angular 2

Here's an Angular 2 tutorial that focuses on how a child component can interact with a parent component using the @Input() property.

By 
Dhananjay Kumar user avatar
Dhananjay Kumar
·
Jan. 02, 17 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
120.0K Views

Join the DZone community and get the full member experience.

Join For Free

in angular 2 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 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 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 childmessage property from the parent component to the greetmessage property of the child component.

intercept input from parent component in 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 _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 pass 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 life cycle hook.

let’s imagine we need to log changes on an input variable called counter. the value of counter is set by the parent component, and can be changed in the parent component. whenever the value of 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 life cycle hook
  2. in ngonchanges method, passing 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!

Property (programming) AngularJS

Published at DZone with permission of Dhananjay Kumar, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Angular Component Tree With Tables in the Leaves and a Flexible JPA Criteria Backend
  • Bing Maps With Angular in a Spring Boot Application
  • Comprehensive Guide to Property-Based Testing in Go: Principles and Implementation
  • Rediscovering Angular: Modern Advantages and Technical Stack

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: