Twitter LogoFacebook Logo
Event Handling
Learn how to bind to events.
By: King Wai Mark

In Angular, you can bind events to a element. 


Binding events means to attach an event listener to listen for any events happening for a particular element in the DOM.

The syntax to bind elements is as follows:

(eventToBind)=""

For example:

<h1 (click)="goToHomePage()">Home</h1>

In the code snippet, we bound the click event to the header element. When the user clicks on the header element, it will call the goToHomePage() function. 

Here are some events that you can bind to:

(click)="myFunction()"      
(dblclick)="myFunction()"   

(submit)="myFunction()"

(blur)="myFunction()"  
(focus)="myFunction()" 

(scroll)="myFunction()"

(cut)="myFunction()"
(copy)="myFunction()"
(paste)="myFunction()"

(keyup)="myFunction()"
(keypress)="myFunction()"
(keydown)="myFunction()"

(mouseup)="myFunction()"
(mousedown)="myFunction()"
(mouseenter)="myFunction()"

(drag)="myFunction()"
(drop)="myFunction()"
(dragover)="myFunction()"

Filtering event keys

Of all the events, the keyup, keydown, and keypress, events can be filtered. This mean that you can specify which key you want to trigger a function. For example, if you want to fire an function when you press a key.


Simply use the period symbol, followed by the name of they key.

<input (keyup.enter)="goToHomePage()" />

In the code snippet, a keyup event is bound to an input element. When the user press the enter key while the input element is focused, it will call the goToHomePage() function.

Demonstration

To demonstrate, follow along with this tutorial. We will add a input element in our app.component.html file and bind they keyup.enter event to it.

<input (keyup.enter)="goToHomePage()" />

In the app.component.ts file, create the goToHomePage() function. This function will just be an alert() message.

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  goToHomePage(){
    alert("GOING TO HOME PAGE");
  }
}

Now, when you start the application using the ng serve command, you should see a button when you go to localhost:4200. When you click on the button, it will pop out an alert, displaying - GOING TO HOME PAGE.

=============

One of the major advantages of using Angular is the ability to easily handle user interactions with the DOM. 


Consider this example:

<div>Hello World</div>

In order for us to give an element in the DOM a click feature, we have to define the element in the HTML page and give it an id so we can reference it later. 

<div id="clickMeExample">Hello World</div>

Once we have done that, we have to write some JavaScript code to get the element and then we can attach an event handler to handle our events.

let clickMeExample = document.getElementById("clickMeExample");


clickMeExample.onclick= () => {
   // Some code
}

Let’s take a look at the same example when we apply Angular. 

<div (click)="clickFunction()">Hello World</div>

clickFunction(){

   // Some code
}

As you can see, we have reduced our code. Not only that, we do not need to give the element an id that we have to remember. If we change the id at some point, we will also have to also change it in the JavaScript code. 

With Angular, all we have to do is to state the event we want to use to in the parenthesis and tell it which function we want it to fire. 

Let’s do an example, open the Angular project on VS Code. Add a div element in the app component html page and bind a click event to it. Use the parenthesis and state the type of event you want it to bind to. Then give it a function that we want it to call when this event happens. 

<div (click)="clickMeExample()">Hello World</div>

Once we have done that, the last thing we need to do is to define that function in the TypeScript file. Go to the app component TypeScript file and define the function.

clickMeExample(){

   alert("Hello World);
}

Save the project and start the local server. Open the browser and go to localhost:4200. Then click on the element.

Image from Codeible.com

As you can see, it is really easy to attach an event handler to a DOM element and react to user interactions.

Let’s do another example. Here is a list of available events. 

(click)="myFunction()"      
(dblclick)="myFunction()"   

(submit)="myFunction()"

(blur)="myFunction()"  
(focus)="myFunction()" 

(scroll)="myFunction()"

(cut)="myFunction()"
(copy)="myFunction()"
(paste)="myFunction()"

(keyup)="myFunction()"
(keypress)="myFunction()"
(keydown)="myFunction()"

(mouseup)="myFunction()"
(mousedown)="myFunction()"
(mouseenter)="myFunction()"

(drag)="myFunction()"
(drop)="myFunction()"
(dragover)="myFunction()"

Let’s use the keyup event. This event gets triggered when we press and let go of a key on the keyboard. 

Go back to VS Code and add an input element to the app component html page. Then bind it with the keyup event and assign a function for it to fire.

<input (keyup)="keyupExample()" />

Tthen go to the app component Typescript to define that function.

keyupExample(){

   alert("Key UP!");
}

Save the project and go to the browser. Click on the input element and press a key.

Image from Codeible.com

You may wonder, how we can get the value of the key that was pressed on. Whenever an event gets triggered, the event will return an $event object with information about the event. We can use that event object that is returned to us and pass it into the function that it is calling and get the value of the key that was pressed. 


Here is what I mean.

Go back to VS Code and then go to the app component html page. The keyup event will return an $event object when it gets fired. So, we can then pass that object into our function and get the key.

<input (keyup)="keyupExample($event)" />

However, we need to make the function accept that object. Go back to the app component TypeScript file and locate the function definition, add a parameter to accept that $event object as an argument.

keyupExample(event){

   alert("Key UP!");
}

The event object contains a property call key which returns the value of the key that was pressed. Store it in a variable and pass it into the alert function. 

keyupExample(event){

   let key = event.key;
   alert(key);
}

Now save the project and go to the browser. When we press and let go of a key, it will print the key that was pressed.

Image from Codeible.com

Recap

Lets take a moment to recap what we have learned.

1. We learned that we can easily implement user interactions in our Angular web application

2. We learned how to bind an event to a DOM element by using the parenthesis and providing the type of event we want it to bind with and then we can handle that event by providing a handler function.

3. We learned that when an event gets triggered, it will return an $event object back to us so that we can use to get the information about the event. 

4. We also learned that we can get the key for key events by taking the $event object and then accessing the key property inside.


Sign In