Event filtering in Angular

Introduction

We have already seen how event binding takes place in Angular. In some scenarios, we want to detect a particular keypress on the keyboard. On pressing a specific key, sometimes we want to trigger some action. In the case of entering input, we want to process the input once the user is finished typing. Generally, we should know when enter is pressed. Pressing enter indicates the end of input. To know when enter key is pressed, we have the following way.

Knowing when enter key is pressed

To know which key is pressed on the keyboard, we will bind some event to it. Keyboard events such as keyup(), keypress(), etc. We have seen in event binding that whenever an event is triggered we will have an associated $event object which has the additional information regarding the event. Every keyboard key has a unique code associated with them. So for the enter key, we have a keycode as 13.  The $event object has a property called keycode. This property uniquely identifies the keys on the keyboard.

@Component({
  selector: 'app-button',
  template: `
      <input (keyup)="manageKey($event)" />

export class AppButtonComponent { 
        manageKey(event){
               // compare key code with code of enter key
               if(event.keyCode === 13) {
                   console.log(‘Enter key pressed’)
               }
       }
   }

In the above example, we have passed the $event to the event handler method. The template has an input box. Whenever user inputs and press enter, we will get a console log.

Event Filtering

When we are deciding when to take action based on some condition such as when to call and execute a particular javascript code. In our case, if the user presses enter then we should call an event. We are filtering the event. 
The above approach is not effective as it will call the manageKey() method every time a key is pressed. It will compare the keycode of every pressed key with keycode of the enter key. 
Angular has an advanced approach for the same. The function is called only when enter is pressed. We can filter the event without $event object also. Let us see the following example. 

@Component({
  selector: 'app-button',
  template: `
      <input (keyup.enter)="manageKey()" />

export class AppButtonComponent { 
        manageKey(){
           console.log("Enter key pressed");        
       }
   }

Comments