Coding exercise: build a parent-child communication example in Angular.
Model answer
Data goes down with input(), and events go up with output(). The parent owns the state, the child displays it and reports what happened.
@Component({
selector: 'app-child',
template: `<button (click)="pressed.emit(step())">Add {{ step() }}</button>`,
})
export class Child {
step = input(1); // data in
pressed = output<number>(); // event out
}
@Component({
selector: 'app-parent',
imports: [Child],
template: `
<p>Total: {{ total() }}</p>
<app-child [step]="5" (pressed)="total.update(t => t + $event)" />`,
})
export class Parent {
total = signal(0);
}Other ways to share data are a shared service (for unrelated components), model() for two-way binding, and viewChild to call a child from the parent. Prefer the simple input and output pair.
Tips
- Older code uses the @Input() and @Output() decorators with EventEmitter; know both.
Practise it yourself in the React and Angular code playground.
Learn this topic
Angular Tutorial: Beginner to Advanced .
Sign in to add your own answer.
More questions
- Coding exercise: build a Todo application in Angular.
- Coding exercise: create a search box with debounce in Angular.
- Coding exercise: fetch API data and display it in a table in Angular.
- Coding exercise: implement pagination in Angular.
- Coding exercise: create a login form with validation in Angular.
- Coding exercise: implement sorting and filtering in Angular.