ng-keydown, ng-keyup, ng-keypress example in angularjs


keydown():   Event fired when a key is pressed on the keyboard
keyup():        Event fired when a key is released on the keyboard
keypress():   Event fired when a key is pressed on the keyboard

From the above definiton both keydown and keypress events look alike, but actually they are not. Keypress event wont work for SHIFT, CTRL and ALT keys. But keydown event will work for all keys. Lets see all these events with example to better understand

Keydown() event :

Syntax
<ng-keydown
ng-keydown="expression">
...
</ng-keydown>

Example 1 
       On every keypress we keep incrementing the count property.

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="">

<input ng-keydown="count = count + 1" ng-init="count=0" />

<h1>{{count}}</h1>

<p>Focus this input field and now press any key on the keyboard</p>

</body>
</html>

Output

Keyup() event
      As said earlier, keyup event if triggered when a key in released in the keyboard and this work for all all keys.

Syntax
<ng-keyup
  ng-keyup="expression">
...
</ng-keyup>

Example -
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="">

<input ng-keyup="count = count + 1" ng-init="count=0" />

<h1>{{count}}</h1>

<p>Focus this input field and now press any key on the keyboard</p>

</body>
</html>


Output
    The output screenshot displays what key is pressed and the counter value


keypress() event
     Keypress is quite special, as this wont work for special keys like SHIFT, CTRL and ALT. Lets see them in action now

Syntax
<ng-keypress
  ng-keypress="expression">
...
</ng-keypress>

Example

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="">

<input ng-keypress="count = count + 1" ng-init="count=0" />

<h1>{{count}}</h1>

<p>Focus this input field and now press any key on the keyboard</p>
</body>
</html>

Output
        The output screenshot displays what key is pressed and the counter value


Hope these example helps and differentiates between keydown event VS keypress event in AngularJS




Reactions:

0 comments :

Post a Comment