Open In App

Event Binding in Angular 8

In Angular 8, event binding is used to handle the events raised by the user actions like button click, mouse movement, keystrokes, etc. When the DOM event happens at an element(e.g. click, keydown, keyup), it calls the specified method in the particular component. 

Using Event Binding we can bind data from DOM to the component and hence can use that data for further purposes.



Syntax:

< element (event) = function() >

Approach: 



Example 1: Using click event on the input element.

app.component.html




<h1>
  GeeksforGeeks
</h1>
<input (click)="gfg($event)" value="Geeks">

app.component.ts




import { Component } from '@angular/core';    
@Component({    
  selector: 'app-root',    
  templateUrl: './app.component.html',    
  styleUrls: ['./app.component.css']    
})    
export class AppComponent {    
  gfg(event) {
    console.log(event.toElement.value);
  }    
}

Output:

Example 2: Using keyup event on the input element.

app.component.html




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

app.component.ts




import { Component } from '@angular/core';    
@Component({    
  selector: 'app-root',    
  templateUrl: './app.component.html',    
  styleUrls: ['./app.component.css']    
})    
export class AppComponent {   
  text = ''
  onKeyUp(x) { 
  
    // Appending the updated value
    // to the variable 
    this.text += x.target.value + ' | '
  
}

Output:


Article Tags :