The @Input()
decorator in Angular is used to pass data from a parent component to a child component. It allows child components to receive data dynamically, enabling better modularization and reusability.
How Does @Input()
Work?
Parent Component: Supplies the data.
Child Component: Accepts the data using @Input()
and uses it in its template or logic.
Create Parent and Child Components
ng generate component parent
ng generate component child
Define Data Flow
Child Component: Use @Input()
In child.component.ts
:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: `
<div>
<h3>Child Component</h3>
<p>Received Message: {{ message }}</p>
<p>Received User: {{ user?.name }} (Age: {{ user?.age }})</p>
</div>
`,
})
export class ChildComponent {
@Input() message!: string; // Input to receive a string
@Input() user!: { name: string; age: number }; // Input to receive an object
}
Parent Component: Send Data
In parent.component.html
:
<div>
<h2>Parent Component</h2>
<app-child
[message]="'Hello from Parent!'"
[user]="{ name: 'John Doe', age: 25 }"
></app-child>
</div>
How It Works
The Parent Component sends:
- A string message:
'Hello from Parent!'
- An object:
{ name: 'John Doe', age: 25 }
The Child Component receives these values via @Input()
and renders them.
Use Aliases for @Input()
If you want to use a custom property name different from the variable name:
In child.component.ts
:
@Input('aliasMessage') message!: string; // Alias for 'message'
In parent.component.html:
//html Copy code
<app-child [aliasMessage]="'Custom Alias Example!'"></app-child>
Handle Changes with OnChanges
The OnChanges
lifecycle hook is triggered whenever the @Input()
values change.
In child.component.ts
:
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
@Component({
selector: 'app-child',
template: `
<div>
<h3>Child Component</h3>
<p>Message: {{ message }}</p>
</div>
`,
})
export class ChildComponent implements OnChanges {
@Input() message!: string;
ngOnChanges(changes: SimpleChanges): void {
console.log('Changes detected:', changes);
}
}
Whenever message
changes, the ngOnChanges
method will log the changes.
Bind Dynamic Data
In parent.component.html
:
<div>
<h2>Parent Component</h2>
<input type="text" [(ngModel)]="parentMessage" placeholder="Enter message" />
<app-child [message]="parentMessage"></app-child>
</div>
In parent.component.ts
:
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
})
export class ParentComponent {
parentMessage: string = 'Initial Message';
}
Key Points to Remember
@Input() allows one-way data binding from parent to child.
Use OnChanges to respond to changes in input properties.
Dynamic bindings (e.g., with ngModel) enable real-time updates.
Pingback: What Is Angular - Tech Mentor