Spread the love

Angular KeyDown Event on Input is an Angular event binding it triggers when user interacts with DOM like text based input element and when we key down the input. Input events in angular can be handled using input and output decorators and in this tutorial we will learn Angular KeyDown Event on Input with Example. In core javascript we use onkeydown event to handle the KeyDown events of input but in angular it there is different way to handle the input events like for key press event we use @output decorator to input element and to handle the event of key up we use (keydown) attribute.

Angular is most popular frontend framework and it has its on guidelines to handle events, forms, rendering etc. In this example we will implement a Simple keydown Event and then we will handle it in typescript component file.

this example of (keydown) in angular will work in all angular version including angular 2, angular 6, angular 7, angular 8, angular 9, angular 10, angular 11, angular 12, angular 13 and angular 14 application.

Simplest way to use keydown is as follow

<input (keydown)="keydown($event)" 
    type="text" 
    placeholder="Enter new PIN" 
/> 
keydown(event: KeyboardEvent) {
  let  keycode = String.fromCharCode(event.charCode);
  console.log("values",event.target.value,keycode);
}

Here we simply assigned the (keydown) to input element and then handled the event in component as above.

Let’s take an example of it

Step 1 : Create an angular app

First step is to setup an angular app using below command

ng new example-app

Step 2: Create a Component

Create a component and a method

ng g c hello-world
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-hello-world',
  templateUrl: './hello-world.component.html',
  styleUrls: ['./hello-world.component.css'],
})
export class HelloWorldComponent implements OnInit {
  
  constructor() {
  }
  keydown(event: any) {
    let  keycode = String.fromCharCode(event.charCode);
    console.log("values",event.target.value,keycode);
  }
  ngOnInit() {}
}

Here we used to keydown method to handle the input

Step 3 : Create template and add html

Now, add simple html template with input field

<h2>Angular keydown Event on Input Example</h2>

<input (keydown)="keydown($event)" 
    type="text" 
    placeholder="Enter new PIN" 
/> 

Leave a Reply