Certainly! Here’s an example of how to use the @Input
decorator in Angular to pass data from a parent component to a child component:
- Create a child component: Let’s create a simple child component that receives data from its parent component.
ng generate component child
In child.component.ts
, define an @Input
property to receive data from the parent component:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: `
<div>
<h2>Child Component</h2>
<p>Data from parent: {{ dataFromParent }}</p>
</div>
`,
})
export class ChildComponent {
@Input() dataFromParent: string;
}
- Create a parent component: In your parent component, you can pass data to the child component using the
@Input
property. Inparent.component.html
, include the child component and bind thedataFromParent
property:
<div>
<h1>Parent Component</h1>
<app-child [dataFromParent]="message"></app-child>
</div>
In parent.component.ts
, define the message
property:
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
})
export class ParentComponent {
message = 'Hello from the parent component!';
}
- Use the parent component: In your app module, make sure to include both the parent and child components in the declarations section of the module.
- Run your application: Run your Angular application to see the
@Input
in action:
ng serve
The child component receives and displays the dataFromParent
value passed from the parent component.