To make an application truly interactive, it must respond to user actions.
Angular achieves this through Event Binding, which captures DOM events (clicks, hovers, keystrokes) and triggers specific methods in your TypeScript component.
As we learned previously, the syntax involves wrapping the event name inside parentheses ( ).
When you bind an event, you assign it a function call from your component's class.
<!-- The template --> <button (click)="onSubmit()">Submit Application</button><!-- Inside the TypeScript component --> onSubmit() { console.log("The button was successfully clicked!"); }
This clean separation ensures your template focuses solely on structure, while TypeScript handles the execution.
Sometimes, you need more information about the event that just occurred.
Angular provides access to the underlying DOM event object through a special variable named $event.
You can pass $event directly into your method to read the user's keystrokes or mouse coordinates.
<!-- Capturing the input value as the user types --> <input type="text" (input)="onSearchChange($event)"><!-- Inside the TypeScript component --> onSearchChange(event: any) { // Extracts the exact text value currently in the input field console.log(event.target.value); }
Often, you only want an event to trigger if a specific keyboard key was pressed.
Instead of manually checking the $event object to see if the "Enter" key was pressed, Angular provides event filters!
You can simply append the key name directly to the event binding.
<!-- The method will ONLY trigger when the Enter key is released --> <input type="text" (keyup.enter)="submitSearch()"><!-- The method will ONLY trigger when the Escape key is released --> <input type="text" (keyup.escape)="clearSearch()">
This makes handling form submissions and search bars exceptionally clean and fast!
What special Angular variable allows you to access the underlying DOM event object (like keystrokes or coordinates) inside your template?
If you want a method to execute ONLY when a user presses the Enter key inside an input field, which syntax is correct?