Open In App

Angular | keyup event

Introduction

Here, we will be explaining the (keyup) event and options that can be used with (keyup) in Angular2. There are various options that can be used with (keyup) event but first let me explain you what is (keyup)
 



(keyup):

(keyup) is an Angular event binding to respond to any DOM event. It is a synchronous event that is triggered as the user is interacting with the text-based input controls. 
When a user presses and releases a key, the (keyup) event occurs. For using in text-based input controls it is generally used to get values after every keystroke. 



Basic Syntax of (keyup)




<input (keyup)="function(parameter)">

Angular provides a corresponding DOM event object in the $event variable which can also be used with (keyup) event to pass values or event.

For passing event syntax will be:




<input (keyup)="keyFunc($event)">

Approach for using (keyup):

Using (keyup) we can call user-defined function which contains the logic to display the text.

Example:

Here in this implementation, $event is passed to user defined function onKeyUp() in typescript file. The function add every value in input after every keystroke to the text variable defined, the text variable is then displayed. 
component.html file




<!-- event is passed to function -->
<input (keyup)="onKeyUp($event)"> 
<!-- text variable is displayed -->
<p>{{text}}</p

component.ts file:




import { Component, OnInit } from '@angular/core';
  
@Component({
  selector: 'app-txtchk',
  templateUrl: './txtchk.component.html',
  styleUrls: ['./txtchk.component.css']
})
export class TxtchkComponent implements OnInit {
  text = ''; //initialised the text variable
  
  ngOnInit(): void {
  }
  onKeyUp(x) { // appending the updated value to the variable
    this.text += x.target.value + ' | ';
  }
  }

Output:

Options for (keyup):

There are many options that can be used with (keyup) event:


Article Tags :