Parent and Child: Inputs and Outputs
PlantList holds all the plants. Each PlantCard shows one and has a Water button. The card needs its plant from the list, and the list needs to hear when the button is pressed. Angular gives each direction its own tool.
The rule
Data flows down through inputs; events flow up through outputs.
The child declares both ends:
import { Component, input, output } from '@angular/core';
@Component({
selector: 'app-plant-card',
template: `
<h3>{{ plant().name }}</h3>
<button (click)="water()">Water</button>
`,
})
export class PlantCard {
plant = input.required<Plant>(); // data coming down
compact = input(false); // optional, with a default
watered = output<number>(); // events going up
water() {
this.watered.emit(this.plant().id);
}
}input()creates a read-only signal the parent fills.input.required<T>()means the parent must supply it;input(false)has a default.output<T>()creates an event the child fires withemit(value).
The parent binds both on the tag:
@for (p of plants(); track p.id) {
<app-plant-card [plant]="p" (watered)="markWatered($event)" />
}[plant]="p" sends data down. (watered)="..." listens, and $event is whatever the child emitted, here the plant's id.
An input signal has no set method. The child cannot overwrite what it was given. That is the point: the component that owns the data is the only one that changes it, so you always know where to look.
Older code uses decorators for the same job, @Input() plant!: Plant; and @Output() watered = new EventEmitter<number>();. The idea is identical.