Angular makes the communication between components very easy. In this article, we will learn how to communicate from a parent component to the child component.
Approach:
Example:
-
In this example, we will create a property
'ParentId'
and receive it in the child component.
Let’s write the code for the parent component.
import { Component } from '@angular/core' ;
@Component({
selector: 'app-root' ,
template:`
<div style= "text-align: center;" >
<h1>
parent component - {{parentid}}
</h1>
</div>
<child [id] = "parentid" ></child>
`,
styleUrls: []
})
export class AppComponent {
parentid: number = 1;
}
|
-
Now write the code for the child component
import { Component, OnInit, Input} from '@angular/core' ;
@Component({
selector: 'child' ,
template: `
<div style= "text-align: center;" >
<h2>child component</h2>
parent id is {{id}}
</div>
`,
styles: []
})
export class TestComponent implements OnInit {
@Input()
id: number;
ngOnInit(): void {
}
}
|
Output:

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!