Sun, Mar 15, 2020
Read in 1 minutes
Introduction : In real-time, you have to pass data or values from one component to another component. In this article, we will explore the ways to pass data from one component to other components.
Passing Data from parent component to child component:
@Input – is used.
app.component.ts:
Declare the data that needs to be passed to the child component. Here in this example , we are going to pass the string ” message” from parent to child component.
message="message from app component";
app.component.html
In the template, you have to mention the child component and pass the message.
<app-child [message]="message">
</app-child>
Child Component :
ChildComponent.ts
Here you have to declare the message string with @Input() decorator.
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
@Input() message:string;
constructor() { }
ngOnInit() {
}
}
ChildComponent.html
<p>
{{message}}
</p>
Output:
parent message in the child component