{ "id": "guide/event-binding-concepts", "title": "How event binding works", "contents": "\n\n\n
\n mode_edit\n
\n\n\n
\n

How event binding workslink

\n

In an event binding, Angular configures an event handler for the target event.\nYou can use event binding with your own custom events.

\n

When the component or directive raises the event, the handler executes the template statement.\nThe template statement performs an action in response to the event.

\n

Handling eventslink

\n

A common way to handle events is to pass the event object, $event, to the method handling the event.\nThe $event object often contains information the method needs, such as a user's name or an image URL.

\n

The target event determines the shape of the $event object.\nIf the target event is a native DOM element event, then $event is a DOM event object, with properties such as target and target.value.

\n

In the following example the code sets the <input> value property by binding to the name property.

\n\n<input [value]=\"currentItem.name\"\n (input)=\"currentItem.name=getValue($event.target)\">\n\n\n

With this example, the following actions occur:

\n
    \n
  1. The code binds to the input event of the <input> element, which allows the code to listen for changes.
  2. \n
  3. When the user makes changes, the component raises the input event.
  4. \n
  5. The binding executes the statement within a context that includes the DOM event object, $event.
  6. \n
  7. Angular retrieves the changed text by calling getValue($event.target) and updates the name property.
  8. \n
\n

If the event belongs to a directive or component, $event has the shape that the directive or component produces.

\n
\n

The type of $event.target is only EventTarget in the template.\nIn the getValue() method, the target is cast to an HTMLInputElement to allow type-safe access to its value property.

\n\ngetValue(target: EventTarget): string {\n return (target as HTMLInputElement).value;\n}\n\n\n
\n\n \n
\n\n\n" }