Component Communication (@Input & @Output)

🅰️ Angular Lesson 5 Beginner

Components often need to share data. In this lesson, we will look at passing data from parents to children using @Input, and triggering notifications upwards using @Output event emitters.

1 Unidirectional Data Flow Channels

Angular components establish explicit boundaries:

  • @Input() Property decorator: Declares a property that a parent component can write data into (downwards flow).
  • @Output() Event emitter decorator: Declares an custom event that a child component can fire upwards, passing data to the parent's event handlers.
2 Child Emitter and Parent Listener setup

Let's check how a child component emits events to its parent:

TypeScript — Child Component
import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-item-card',
  template: `
    

{{ itemTitle }}

` }) export class ItemCardComponent { @Input() itemTitle: string = ''; @Output() selected = new EventEmitter(); selectItem() { this.selected.emit(this.itemTitle); } }

The parent component binds to these decorators in its HTML template:

HTML — Parent Binding Template
<app-item-card 
  [itemTitle]="parentTitle" 
  (selected)="onItemSelect($event)">
</app-item-card>
3 Code Challenge
Challenge: Build a child component CounterControlsComponent that contains increment and decrement buttons, emitting values of +1 or -1 back to a parent count variable.