From 66b4c89b6feb44d1cab26656944d1ac2888fc80a Mon Sep 17 00:00:00 2001 From: Jan Martin Date: Wed, 7 May 2025 08:48:57 -0700 Subject: [PATCH] docs: document `preventDefault()` behavior for event listeners (#61184) The `false` behavior has existed for a long time but hasn't really been documented. It's also not _quite_ what the browser would do. Finally, the page explicitly discourages the implicit `false` way of preventing default. Biggest motivation (beyond code clarity) are potential footguns like `(click)="myProp=x()"` which happens to prevent default behavior iff `x()` happens to return `false`. Fixes https://github.com/angular/angular.io/issues/2568 PR Close #61184 --- .../guide/templates/event-listeners.md | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/adev/src/content/guide/templates/event-listeners.md b/adev/src/content/guide/templates/event-listeners.md index 2623dd9f1ce..f8c10ded461 100644 --- a/adev/src/content/guide/templates/event-listeners.md +++ b/adev/src/content/guide/templates/event-listeners.md @@ -97,3 +97,24 @@ Angular also allows you to specify [Code values for keyboard events](https://dev ``` This can be useful for handling keyboard events consistently across different operating systems. For example, when using the Alt key on MacOS devices, the `key` property reports the key based on the character already modified by the Alt key. This means that a combination like Alt + S reports a `key` value of `'ß'`. The `code` property, however, corresponds to the physical or virtual button pressed rather than the character produced. + +## Preventing event default behavior + +If your event handler should replace the native browser behavior, you can use the event object's [`preventDefault` method](https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault): + +```angular-ts +@Component({ + template: ` + + `, + ... +}) +export class AppComponent{ + showOverlay(event: PointerEvent): void { + event.preventDefault(); + console.log('Show overlay without updating the URL!'); + } +} +``` + +If the event handler statement evaluates to `false`, Angular automatically calls `preventDefault()`, similar to [native event handler attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Attributes#event_handler_attributes). *Always prefer explicitly calling `preventDefault`*, as this approach makes the code's intent obvious.