Input decorator in Angular

Nitin Manocha
Sep 1, 2018 · 2 min read

In Angular, components can communicate with each other using following methods:

Passing the reference of one component to another

Communication through Service

In this, We are going to learn how data passes from parent component to child component using Input decorator.
We have created two components- Parent component and Child component.

Parent component — app.component.ts
Child component — child.component.ts

In order to use Input decorator, We have to import it from angular core using the following command:
import { Input } from ‘@angular/core’;

Lets understand this with code.

File: app.component.ts

import { Component} from ‘@angular/core’;

@Component({

selector: ‘app-root’,

templateUrl: ‘./app.component.html’,

styleUrls: [‘./app.component.css’]

})

export class AppComponent
{

title = ‘App’;

parent=’This data is of parent component’

}

In this, we have created a property ‘parent’ which we are going to pass into our child component.

File: child.component.ts

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

@Component({
selector: ‘child-app’,
template:`<h1>{{child}}</h1>`
})

export class ChildComponent {
title = ‘App’;
@Input() child: string;
}

Here, We have created another property ‘child’ of string type and used Input decorator to get the data from parent component

File: app.component.html

<child-app [child]=’parent’> </child-app>

In this, ‘child’ property of Child component is getting data from ‘parent’ property of parent component.

Now, Start your application and see the result.

Output

This is how we pass data or property from parent component to child component using Input decorator.
In the next part, We’ll learn how to pass data from child component to parent component using Output decorator.

For any query or suggestion, you can get in touch with me on Twitter.

Written by

NodeJs Developer | Microsoft Student Partner | https://nitinmanocha.in

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade