Event Binding In Angular
In this article, we learn about the Angular Event Binding. One approach from view to component is by event binding. When the user takes an action in the view, like as clicking a button or altering the input, we use it to conduct an action in the component.
We may connect events like keystrokes, clicks, hovers, and touches to a method in a component using event binding. From view to component, there is only one path. We may maintain our component in sync with the view by tracking and responding to user events in the view. When a user updates an input in a text box, for example, we can update the component's model, run some validations, and so on. We can store the model to the backend server after the user submits the button.
Syntax Of Event Binding
There are two parts to the Angular event binding.
(target-event)="TemplateStatement"
<button (click)="onSave()">Save</button>
Example Of Event Binding
ng new event-Binding
<h1 [innerText]="title"></h1> <h2>Example 1</h2> <button (click)="clickMe()">Click Me</button> <p>You have clicked {{clickCount}}</p>
clickCount=0
clickMe() {
this.clickCount++;
}
Multiple event handlers
clickCount1=0;
//Template
<h2>Example 2</h2>
<button (click)="clickMe() ; clickCount1=clickCount">Click Me</button>
<p>You have clicked {{clickCount}}</p>
<p>You have clicked {{clickCount1}}</p>
$event Payload
<input (input)="handleInput($event)">
<p>You have entered {{value}}</p>
value=""
handleInput(event) {
this.value = (event.target as HTMLInputElement).value;
}
Key event filtering
<input (keyup)="value1= $any($event.target).value" />
<p>You entered {{value1}}</p>
<input (keyup.enter)="value2=$any($event.target).value">
<p>You entered {{value2}}</p>
<input (keyup.enter)="value3=$any($event.target).value" (keyup.escape)="$any($event.target).value='';value3=''"> <p>You entered {{value3}}</p>