How to communicate from parent component to the child component in Angular 9 ?
Last Updated :
11 Jun, 2020
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:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...