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.