Component Interaction in Angular:
Angular is a powerful front-end framework built around a component-based architecture. In any Angular application, components do not exist in isolation—they interact with each other to build cohesive applications.
In this article, we’ll explore the different ways Angular components can interact, common use cases, and best practices to ensure a clean and maintainable structure.
1. Introduction to Angular Components
An Angular component is a TypeScript class decorated with @Component. It includes:
An HTML template
A TypeScript class for logic
A CSS/SCSS file for styling
Example:
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.scss']
})
export class MyComponent {
title = "Welcome";
}
🔄 2. Types of Component Interaction
Component interaction depends on their hierarchical relationship:
| Interaction Type | Description |
| Parent → Child | The parent passes data to the child using @Input() |
| Child → Parent | The child emits events to the parent using @Output() + EventEmitter |
Direct Access via @ViewChild() | The parent can call methods/properties of the child |
| Shared Services | For distant or unrelated components |
| Communication via RxJS/Observables | For reactive and advanced communication flows |
In this article, we will look at how to use the first 3 methods.
📥 3. Parent to Child: @Input()
This is the most direct way to pass data from a parent to a child component.
Example:
Parent template:
<app-child [message]="parentMessage"></app-child>
Parent.ts:
export class ParentComponent {
parentMessage = "Hello from the parent!";
}
Child.ts:
tsCopyEditexport class ChildComponent {
@Input() message!: string;
}
Child.html:
<p>{{ message }}</p>
📤 4. Child to Parent: @Output() and EventEmitter
Used when the child needs to notify the parent of an event (click, update, etc.).
Example:
Child.ts:
@Output() alert = new EventEmitter<string>();
sendAlert() {
this.alert.emit("Alert from the child!");
}
Child.html:
<button (click)="sendAlert()">Alert Parent</button>
Parent.html:
<app-child (alert)="handleAlert($event)"></app-child>
Parent.ts:
handleAlert(message: string) {
console.log("Received message:", message);
}
🔍 5. Direct Access with @ViewChild()
Allows the parent to directly access a child component instance and call its methods.
Example:
Child.ts:
export class ChildComponent {
sayHello() {
console.log("Hello!");
}
}
Parent.ts:
@ViewChild(ChildComponent) childComponent!: ChildComponent;
ngAfterViewInit() {
this.childComponent.sayHello();
}



