Component Communication
In real applications, components rarely work in isolation. They need to talk to each other – parent to child, child to parent, or even unrelated components. Angular provides several ways for component communication.
1. Parent to Child: @Input()
Pass data from parent to child using the @Input decorator.
// child.component.ts
@Component({
selector: 'app-child',
template: `<p>Hello, {{ name }}!</p>`
})
export class ChildComponent {
@Input() name: string;
}
// parent.component.ts
@Component({
selector: 'app-parent',
template: `<app-child [name]="parentName"></app-child>`
})
export class ParentComponent {
parentName = 'John';
}
2. Child to Parent: @Output() and EventEmitter
Emit events from child to parent using EventEmitter.
// child.component.ts
@Component({
selector: 'app-child',
template: `<button (click)="sendData()">Send</button>`
})
export class ChildComponent {
@Output() dataEvent = new EventEmitter();
sendData() {
this.dataEvent.emit('Hello from child!');
}
}
// parent.component.ts
@Component({
selector: 'app-parent',
template: `
<app-child (dataEvent)="handleData($event)"></app-child>
<p>Message: {{ message }}</p>
`
})
export class ParentComponent {
message: string;
handleData(data: string) {
this.message = data;
}
}
3. Unrelated Components: Using a Service
For components that aren't directly related, use a shared service with Observables.
// data.service.ts
@Injectable({ providedIn: 'root' })
export class DataService {
private messageSource = new BehaviorSubject('');
currentMessage = this.messageSource.asObservable();
changeMessage(message: string) {
this.messageSource.next(message);
}
}
Two Minute Drill
- @Input passes data from parent to child.
- @Output with EventEmitter sends events from child to parent.
- Use template reference variables (#var) for parent to access child methods directly.
- Use a shared service with Observables for unrelated components.
- Choose the right communication method based on component relationship.
Need more clarification?
Drop us an email at career@quipoinfotech.com
