Event Binding and Template Statements
A plant card that cannot be watered is just a picture. Buttons, text boxes and key presses need to reach the class. Round brackets carry those events from the template into your code.
The rule
Round brackets listen; the statement inside should just call a method.
<button (click)="water()">Water</button>When the button fires click, Angular runs the template statement water(). Unlike an expression, a statement is allowed to do things, but keep it to a method call. Real logic belongs in the class, where it can be read and tested.
To use the event itself, pass $event:
<input (input)="onType($event)" />draft = signal('');
onType(e: Event) {
const box = e.target as HTMLInputElement;
this.draft.set(box.value);
}What $event holds depends on the source:
- A native DOM event (
click,input,submit) gives the browser's event object. - A component output, like
(watered)from the last section, gives whatever the child emitted.
Angular also offers key filters, so you do not have to check e.key yourself:
<input (keydown.enter)="addPlant()" (keydown.escape)="clear()" />A template reference variable often removes the need for $event entirely. #box names the element, and statements can use it:
<input #box />
<button (click)="addPlant(box.value)">Add</button>Statements see the component's members, $event and template variables, but not globals such as window or alert.
The shortcut
Read (event)="statement" as "when event, do statement". Then check two things: does the statement need data from the event (pass $event or a #ref), and is it longer than one method call (move it into the class).
When what?
When Enter is pressed in the name box:
(keydown.enter).
Drills
Answer fast — trust the rule.
For (click)="water($event)" on a <button>, what is $event?
Which binding runs save() only when Enter is pressed?
<input #box /> sits next to a button. How can the button's click pass the typed text?
Why might (click)="alert('Watered!')" fail?
Remember
(event)="statement"means "when event, do statement".$eventis the DOM event for native events and the emitted value for component outputs;#refnames an element.- Trap: logic piled into the template; keep one method call and move the rest to the class.
