In an Angular app, components often need to talk to each other to share data and trigger actions. But just like in real life, good communication matters! If it's messy, your app becomes hard to manage.
So, how do Angular components communicate efficiently? Here’s a Simple Analogy.🚀
Think of a parent component as a manager giving instructions to a team member (child component).
How? Using the @Input decorator.
🛠 Example:
Imagine a UserListComponent (parent) sending a username to UserCardComponent (child).
// Parent Component (user-list.component.ts)
<app-user-card [username]="userName"></app-user-card>
// Child Component (user-card.component.ts)
@Input() username: string;
Use @Input when the parent needs to pass data to the child.
Now, let’s say the team member (child) wants to report progress back to the manager (parent).
How? Using @Output and EventEmitter.
Example:
A child button component informs the parent when it’s clicked.
// Child Component (button.component.ts)
@Output() buttonClicked = new EventEmitter<void>();
onClick() {
this.buttonClicked.emit();
}
// Parent Component (app.component.html)
<app-button (buttonClicked)="handleClick()"></app-button>
Use @Output when the child needs to notify the parent.
Think of two sibling components as coworkers passing notes via a shared message board (a service).
How? By creating a shared service with BehaviorSubject or RxJS Observables.
Example:
A CartService allows a ProductList component to update a Cart component.
// Shared Service (cart.service.ts)
@Injectable({ providedIn: 'root' })
export class CartService {
private cart = new BehaviorSubject<number>(0);
cartCount$ = this.cart.asObservable();
updateCart(count: number) {
this.cart.next(count);
}
}
// Component 1 (ProductList) updates the cart
this.cartService.updateCart(newCount);
// Component 2 (CartComponent) listens for changes
this.cartService.cartCount$.subscribe(count => this.cartCount = count);
Use a shared service when unrelated components need to exchange data.
If your app is big and data needs to be accessible everywhere, you need a state management tool like NgRx (Redux pattern).
How? Using a centralized store that keeps track of app-wide data.
Example:
An authentication service that stores user login state and makes it available globally.
Use NgRx when managing large-scale state across multiple components.
Parent → Child
Child → Parent
Sibling ↔ Sibling
Global State
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our Angular Expertise.
Contact Us