Event Binding
Responding to clicks, keystrokes, and other user actions in the template with Angular's event binding syntax.
2 menit membaca
Property binding sends data from the class into the template. Event binding sends information the other way — from something the user does in the template back into the class.
The basic syntax
<button (click)="save()">Save</button>
<input (input)="onSearch($event)" />
<form (submit)="onSubmit($event)">...</form>export class SearchBoxComponent {
results: string[] = [];
save(): void {
console.log('Saving...');
}
onSearch(event: Event): void {
const value = (event.target as HTMLInputElement).value;
this.results = this.results.filter((r) => r.includes(value));
}
}Parentheses mark an event binding, and the name inside them (click, input, submit) is a native DOM event. Whatever expression is on the right runs when that event fires — usually calling a method on the component.
The $event object
Angular passes the native event object through automatically if you ask for it by name: $event. For a click, that's a MouseEvent; for input, it's an Event whose target is the input element that triggered it. Typing event.target as HTMLInputElement (as above) is necessary because TypeScript only knows it as a generic EventTarget otherwise — casting it is what lets you safely read .value.
Preventing default behavior
Forms are a common place you need to stop the browser's default action — a normal HTML form submission reloads the page:
<form (submit)="onSubmit($event)">
<input name="email" />
<button type="submit">Subscribe</button>
</form>onSubmit(event: Event): void {
event.preventDefault();
console.log('Handling submission in Angular instead of reloading the page');
}Calling event.preventDefault() inside the handler stops the native reload, letting the component manage what "submitting the form" actually does.
Custom events, not just DOM events
Event binding isn't limited to built-in DOM events. A child component can define and emit its own custom events for a parent to listen to — the exact same (eventName)="handler($event)" syntax works for those too. You'll see how a component defines a custom event in the lesson on @Input and @Output; from the listening side, there's no difference between reacting to a native click and reacting to a child component's own (itemSelected) event.
Keeping handlers small
Because a template expression like (click)="save()" runs directly, it's tempting to write more logic straight into the template: (click)="items = items.filter(i => i.done)". Resist that for anything beyond a one-line toggle — logic embedded in a template is harder to test and to read than the same logic named as a method on the class.