To bind to an event, use Angular’s event binding syntax. This syntax consists of the target event name in parentheses to the left of the equals sign and the template statement in quotes to the right. In the following example, the target event name is click and the template statement is onSave().

<button (click)="onSave()">Save</button>

The event binding listens for button clicks and calls the component’s onSave() when a click occurs.

An example from Spartacus:

$event is the event object.

The $event object typically contains information required for the method, such as a user name or image URL.

The target event determines the shape of the $event object. If the target event is from a native DOM element, then $event is a DOM event object with attributes such as target and target.value.

Look at this example:

<input [value]="currentItem.name"
       (input)="currentItem.name=getValue($event)">
  • The value of the input control is bound to the currentTem. name property of the Component.

The input event of the input control, when fired, assigns the result returned by getValue to the Component property currentTem.Name

This binding executes the statement in a context that contains the DOM event object $event.

Angular gets the changed text by calling getValue($event.target) and uses it to update the name property.

In the template, the type of $event.target is simply EventTarget. In the getValue() method, the target is converted to the HTMLInputElement type to allow type-safe access to its value attribute.

The Spartacus example shows how TypeScript code can determine whether a button is triggered by a mouse click or a keyboard stroke when a user interacts with a button.

close(event: MouseEvent | KeyboardEvent) { event.preventDefault(); if (event instanceof MouseEvent) { this.eventSubject.next(PopoverEvent.CLOSE_BUTTON_CLICK); } else { this.eventSubject.next(PopoverEvent.CLOSE_BUTTON_KEYDOWN); }}

More of Jerry’s original articles can be found on “Wang Zixi “: