Read More on Telerik Blogs
September 07, 2021 Web, Angular
Get A Free Trial

Data binding can be confusing when you’re getting started in Angular. Let’s break it down! This post covers event binding, which is one of the one-way data binding methods.

This is the second post in the data binding in Angular series. If you have not, you can take a look at the interpolation post here. In this post, we will look at how to do event binding in Angular.

Before We Start

This post is suited for all levels of frontend developers who use Angular, so being conversant with beginner concepts and installation processes is not assumed.

Here are a few prerequisites you should have to follow this article’s demonstration with Angular 12:

  • Visual Studio Code as your integrated development environment
  • Node version 11.0 installed on your machine
  • Node Package Manager version 6.7 (it usually ships with Node installation)
  • Angular CLI version 8.0 or above
  • The latest version of Angular (version 12)
// run the command in a terminal
ng version

Confirm that you are using version 12, and update to 12 if you are not.

Other things that will be nice-to-haves are:

  • Working knowledge of the Angular framework at a beginner level

Events in Angular

One of the reasons frontend development frameworks like Angular are so popular is because of the interactivity you can get by utilizing easy-to-use features. One of those features is event binding.

When you have an application, it is very important that you think about user-initiated interactions. User-initiated interactions are basically what happens when a user executes an event. These events can range from clicking a button or a portion of the DOM, to inputting data in a form or hovering over a button.

Event Binding

Angular lets you handle these user-initiated interactions in the best way. With Angular, you can check for a specific event and then bind or trigger specific actions that should happen when those events are detected. This is the whole idea of event binding and it is a one-way data-binding process from the view to the component.

What We Are Building

We are going to build a sample Angular application using the Kendo UI Template Wizard in VS Code and show how to set up event binding to some example events.

Open up your VS Code application and go to the Command Palette (type Command + Shift + P on Mac or Ctrl + Shift + P on PC) to open the Kendo UI Wizard. If you do not have the Kendo UI Wizard installed already, then go to the Extensions tab, search for Kendo UI Template Wizard and install it. Restart the VS Code app and then go back to the Command Palette to open the Kendo UI Wizard.

Choose a project name and a location on your machine where you want it to be saved, and click “Next.”

Choose Angular and then choose blank with 1 page and click “Next.”

Choose default CSS as your style choice and click “Create.” Once it finishes, click on “Open new project.” Open the terminal and download all the Node dependencies with this command:

npm install

After that, you can run the application on the dev server with this command:

ng serve

The application should look like this if you visit localhost:4200 in your browser.

Now let us look at a few events and how we can bind them to our chosen interactions in our application.

Keyboard Events

There are a lot of keyboard events. Some of them are keyup, keydown and keypress, which all occur when you press a key on your keyboard. Keydown refers to the depression on the press. Keyup refers to that exact moment when you let go of a key after press. Keypress refers to the press itself. Let us create a modal on keypress and then log some strings on keyup and keydown.

Keypress

For keypress, navigate to the app.component.html file and replace the content with the code block below:

<div class="content">
    <app-header></app-header>
    <router-outlet>
        <input (keypress)="pressFunction()">
    </router-outlet>
   
</div>
<div class="footer">
    <app-footer></app-footer>
</div>

You can see the input field we introduced in the view and what we did was to tell Angular that, whenever any key is pressed inside that input field, to let the function called “press Function” execute. To define the press function, go to the app.component.ts file and define the function like this:

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
pressFunction(){
    alert('You just pressed a key')
   }
}

Now we have set up the function to pop up a modal that tells you that you have pressed a key.

Keyup and Keydown

Just as we earlier discussed, when you click any key on the keyboard, the moment you depress the key can be recorded as keydown and the exact moment you let go of the key can be recorded as keyup. Think of them as the lifecycle of buttons on the keyboard. Now let us define logs on the console when keys are pressed for keyup and keydown.

<div class="content">
    <app-header></app-header>
    <router-outlet>
        <h3>
            Input for key press
        </h3>
        <input (keypress)="pressFunction()"> <br>
        <h3>
            Input for key up
        </h3>
        <input (keyup)="upFunction()" (keydown)="downFunction()"> <br>
    </router-outlet>
    
</div>
<div class="footer">
    <app-footer></app-footer>
</div>

In the component file, add the functions below:

upFunction(){
    console.log('You just released the key you pressed')
  }
  downFunction(){
    console.log('You just depressed a keyboard button')
  }

If you save the files and look at your browser, you should see that the keydown is triggered first before keyup, just as you would expect.

Click Events

Event binding works on every single DOM event type, so let’s test it out on click events.

Add this button to the template:

<button (click)=”clickFunction()”>New Button</button>

In the component file, update it with the click function below:

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
pressFunction(){
    alert('You just pressed a key')
  }
  upFunction(){
    console.log('You just released the key you pressed')
  }
  downFunction(){
    console.log('You just depressed a keyboard button')
  }
clickFunction(){
    alert('You just clicked a button')
  }
}

If you save the file you should see the alert pop up as you click the button.

Conclusion

We have seen the basics of event binding in Angular—why event binding is important for designing interactive solutions for your customers. We saw a few events and how to easily set up event binding. Make sure to stay tuned as we have more posts on data binding in Angular on the blog. Happy hacking!


About the Author

Nwose Lotanna Victor

Nwose Lotanna Victor is a web technology enthusiast who documents his learning process with technical articles and tutorials. He is a freelance frontend web developer based in Lagos, Nigeria. Passionate about inclusion, community-building and movies in Africa, he enjoys learning new things and traveling.

Related Posts