AngularJS – ng-keydown Directive


The ng-keydown directive in AngularJS basically specifies a custom event on pressing the <down> key. We can perform multiple functions whenever the keydown event is called. This event also supports different types of elements like <input>, <select> and <textarea>.

Syntax

<element ng-keydown="expression">..content..</element>

Example − ngKeydown Directive

Create a file "ngKeydown.html" in your Angular project directory and copy-paste the following code snippet.

<!DOCTYPE html>
<html>
   <head>
      <title>ngKeydown Directive</title>

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

      <style type="text/css">
         .keyDown {
            background-color: blue;
            color: white;
         }
         .keyUp {
            background-color: white;
         }
      </style>
      </head>

      <body ng-app style="text-align: center;">
      <h1 style="color:green">
         Welcome to Tutorials Point
      </h1>
         <h2>
            AngularJS | ngKeydown Directive
      </h2>

      <div>
         <b>Enter Name: </b><input type="text"
         ng-model="searchValue" ng-keydown="keyDown=true"
         ng-keyup="keyDown=false" ng-class=
         "{true:'keyDown', false:'keyUp'}[keyDown]" />

         <br>
      </div>

   </body>
</html>

Output

To run the above code, just go to your file and run it as a normal HTML file.

On keyDown −


Example 2

Create a file "ngKeydown.html" in your Angular project directory and copy-paste the following code snippet.

<!DOCTYPE html>
<html>
   <head>
      <title>ngKeydown Directive</title>

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

      </head>

      <body ng-app style="text-align: center;">
      <h1 style="color:green">
         Welcome to Tutorials Point
      </h1>
         <h2>
            AngularJS | ngKeydown Directive
      </h2>

      <div>
         <input ng-keydown="count = count + 1" ng-init="count=0">
         key down count: {{count}}
      </div>

   </body>
</html>

Output

To run the above code, just go to your file and run it as a normal HTML file.

Will count the occurrence of keydown events −

Updated on: 08-Oct-2021

217 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements