Input decorator in Angular

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’;
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.

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.
