Related Articles

Related Articles

Event Binding in Angular 8
  • Last Updated : 14 Sep, 2020

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: 

  • Define a function in the app.component.ts file which will do the given task.
  • In the app.component.html file, bind the function to the given event on the HTML element.

Example 1: Using click event on the input element.



app.component.html

HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


app.component.ts

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

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);
  }    
}

chevron_right


Output:

Example 2: Using keyup event on the input element.

app.component.html

HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


app.component.ts

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

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 + ' | '
  
}

chevron_right


Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :