mirror of
https://github.com/angular/angular.git
synced 2026-09-14 13:54:52 +08:00
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
This commit is contained in:
committed by
Andrew Kushnir
parent
fb62506894
commit
66b4c89b6f
@@ -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: `
|
||||
<a href="#overlay" (click)="showOverlay($event)">
|
||||
`,
|
||||
...
|
||||
})
|
||||
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.
|
||||
|
||||
Reference in New Issue
Block a user