Sub topic 2
Responding to Events with Event Binding
This chapter assumes you know DOM events, TypeScript classes, and the interpolation and property bindings from the previous chapter. Data has so far flowed from component to template. Here it flows back.
Event Binding
An event binding puts the DOM event name in parentheses. Angular runs the statement on the right each time the event fires. $event holds the native event object.
import { Component } from '@angular/core';
@Component({
selector: 'app-echo',
template: `
<input (input)="onInput($event)">
<p>You typed: {{ value }}</p>
`,
})
export class EchoComponent {
value = '';
onInput(event: Event) {
this.value = (event.target as HTMLInputElement).value;
}
}A common error is writing $event.target.value directly in the template. Under strict template checking this fails, because target is typed as EventTarget | null. Cast it in the component, as shown above.
Template Reference Variables
A template reference variable, written #name, gives you a handle on an element inside the template. You don't need $event to use it:
import { Component } from '@angular/core';
@Component({
selector: 'app-todo',
template: `
<input #box (keyup.enter)="add(box.value); box.value = ''">
<ul>@for (t of todos; track $index) { <li>{{ t }}</li> }</ul>
`,
})
export class TodoComponent {
todos: string[] = [];
add(text: string) { this.todos.push(text); }
}Two-Way Binding: Banana in a Box
[(x)]="field" is shorthand. It combines [x]="field" with (xChange)="field = $event". The brackets sit outside the parentheses, which is why it's called "banana in a box". Writing ([x]) is a frequent typo, and Angular rejects it.
ngModel on Form Controls
Native inputs have no valueChange event. NgModel from FormsModule fills that gap:
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-greeting',
imports: [FormsModule],
template: `
<input [(ngModel)]="name">
<p>Hello, {{ name }}!</p>
`,
})
export class GreetingComponent {
name = 'World';
}Parent-Child Data with @Input and @Output
@Input receives data through property binding. @Output exposes an EventEmitter that the parent listens to with event binding.
import { Component, EventEmitter, Input, Output } from '@angular/core';
@Component({
selector: 'app-item',
template: `<button (click)="remove.emit(id)">Remove {{ id }}</button>`,
})
export class ItemComponent {
@Input() id = 0;
@Output() remove = new EventEmitter<number>();
}The parent uses it as <app-item [id]="7" (remove)="onRemove($event)" />. In the parent's handler, $event is the emitted number, not a DOM event.
Exercise
A child component has @Input() size and @Output() sizeChange. What does <app-box [(size)]="width"> expand to?
Show answer
<app-box [size]="width" (sizeChange)="width = $event">. The output name must be the input name followed by Change for the banana-in-a-box syntax to work.