Component Deep Dive
@Input & @Output
Parent-Child Communication
💡 @Input ek parent se child ko GIFT bhejना hai (data neeche jaata hai). @Output ek child se parent ko MESSAGE bhejना hai (event upar jaata hai, jaise ek employee apne manager ko update deta hai) — "unidirectional data flow" ka core pattern.
@Input() decorator ek property ko "input" banata hai — PARENT component isse VALUE pass kar sakta hai. @Output() decorator + EventEmitter ek property ko "output" banata hai — CHILD component isse EVENT emit kar sakta hai, jo parent SUNTA hai.
// child.component.ts:
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: `
<p>{{ message }}</p>
<button (click)="sendUpdate()">Update Parent</button>
`
})
export class ChildComponent {
@Input() message = ''; // parent se aata hai
@Output() updated = new EventEmitter<string>(); // parent ko jaata hai
sendUpdate() {
this.updated.emit('Child se update!');
}
}
// parent.component.html:
// <app-child [message]="parentMessage" (updated)="onChildUpdate($event)"></app-child>↔️
@Input ek parent se child ko GIFT bhejना hai (data neeche jaata hai). @Output ek child se parent ko MESSAGE bhejना hai (event upar jaata hai, jaise ek employee apne manager ko update deta hai) — "unidirectional data flow" ka core pattern.
1 / 2
⚡ Quick Recap
- @Input() = parent se child ko data (neeche)
- @Output() + EventEmitter = child se parent ko event (upar)
- Unidirectional flow = predictable, debug-friendly
On this page (2 subtopics)
@Input() property ko ek "setter" method mein convert kar sakte ho — jab bhi parent naya value pass kare, setter automatically chalता hai, custom logic (jaise validation, transformation) run karne ke liye.
export class PriceComponent {
private _price = 0;
@Input()
set price(value: number) {
this._price = value < 0 ? 0 : value; // negative prices allow nahi
}
get price(): number {
return this._price;
}
}Tip: ngOnChanges() bhi similar kaam kar sakta hai (SimpleChanges object deta hai, jisme currentValue/previousValue dono milte hain), lekin setter approach single-property logic ke liye zyada concise hai.
@Output() event names PAST TENSE ya "action completed" jaisa naam rakhte hain (jaise valueChanged, itemSelected, na ki select ya change directly) — HTML native events (click, change) se naming clash avoid karta hai.
// GOOD naming:
// @Output() itemSelected = new EventEmitter<Item>();
// @Output() formSubmitted = new EventEmitter<FormData>();
// AVOID (clashes with native DOM events):
// @Output() click = new EventEmitter<void>(); — confusing!Tip: Angular style guide explicitly recommend karta hai native event names avoid karne ki — confusion hota hai ki (click) native DOM event hai ya custom @Output, especially bade codebases mein.