Ng-Keypress in AngularJS

Rana Hasnain Khan May 27, 2022
Ng-Keypress in AngularJS

We will introduce ng-keypress in AngularJS with examples.

Use ng-keypress in AngularJS

While working on an AngularJS application, there are many situations when we need to assign a behavior on a keypress. To apply custom behavior on a keypress, we have to use the ng-keypress directive in an AngularJS.

The ng-keypress mandate from AngularJS will not supersede the components unique to the keypress occasion; both will be executed. This is supported by <input>, <select> and <textarea> element.

Syntax:

# angularjs
<input ng-keypress="behavior">

The "behavior" will determine what to do when the key is pressed.

Let’s have an example and use this ng-keypress directive. First, we will create the view in index.html.

Code - index.html:

# angularjs
<!DOCTYPE html>
<html>

<head>
    <title>ng-keypress Directive By Rana Hasnain</title>

    <script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
    </script>

    <script type="text/javascript" src="app.js"></script>
</head>

<body style="text-align:center">
    <div ng-app="ngApp" ng-controller="ngController">
        <h1 style="color:Blue">
            Delft Stack
        </h1>

        Enter Name: <input type="text"
                ng-keypress="getKeyVal($event)" >

        <br><br>

        <span style="color:green;">
            Code of Key Is: {{valKey}}
        </span>
    </div>
</body>
</html>

Next, we create a function to get the key values in app.js.

Code - app.js:

# angularjs
var app = angular.module('ngApp', []);
        app.controller('ngController', function ($scope) {
            $scope.getKeyVal = function (event) {
                $scope.valKey = event.keyCode;
            }
        });

Output:

ng keypress in angularjs example

Rana Hasnain Khan avatar Rana Hasnain Khan avatar

Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.

LinkedIn

Related Article - Angular Directive