Angular 10 Tutorial - Event Binding
In this tutorial, we will learn about event binding in Angular 10. When a user interacts with an application in the form of keyboard typing, a mouse click, or a mouseover, it generates an event. These events need to be handled to perform some kind of action. This is where event binding comes into the picture.
Handling Click Events
Let's see how we can do event binding. First, let's see the click event. Switch to the project and inside the project, open the app.component.html file and add a button:
<button>Increase One</button>
Now, go to the app.component.ts file and add a property and also create a function:
count = 0;
increementByOne()
{
return num++;
}
Now, add this function to the button. Go to the app.component.html file and write:
<button (click) = "increementByOne()" >Click Me</button>
Now, let's display the count value. Write:
<h1>{{count}}</h1>
Alright, now let's check it. Switch to the browser and now click on the button. And here you can see the number is increasing by one.
Handling Mouse Move Events
Now, let's see the mousemove event. Go to the app.component.html file and create a div:
<div (mousemove) = "increementByOne()" style="background:blueviolet;height:200px;width: 200px;"> </div>
Now, add the event mousemove and call the incrementByOne function. Now, let's check it. Move the mouse on this div. And here you can see the number is increasing by one.
Handling Change Events
Now, let's see the change event. For that, just create a select:
<select name="color">
<option value="Red">Red</option>
<option value="Blue">Blue</option>
<option value="Green">Green</option>
<option value="Orange">Orange</option>
</select>
Now, create a function inside the app.component.ts file:
color='';
changeColor(color)
{
this.color=color;
}
Now, add this function to the select:
<select name="color" (change)="changeColor($event.target.value)">
Now, just print the selected color. Write:
<h1>Selected Color : {{color}}</h1>
Now, let's check this. Go to the browser and just change the color. And here you can see the selected color. If you select green, the selected color is green.
Handling KeyDown Events
Now, let's see the keyDown event. Go to the app.component.html file and add an input field:
<input type="text" />
Now, create a function for handling the keydown event:
text = '';
handleKeydown(text)
{
this.text=text;
}
Now, add this event to the text box:
<input type="text" (keydown) = "handleKeydown($event.target.value)" />
Now, display the text:
<h1>Text : {{text}}</h1>
Now, let's check it. Switch to the browser and here just type inside the text field. You can see here the typed text.
So, in this way, you can bind events in Angular 10.