Event Binding in Angular 8
Last Updated :
14 Sep, 2020
Improve
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
< h1 > GeeksforGeeks </ h1 > < input (click)="gfg($event)" value = "Geeks" > |
app.component.ts
Javascript
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
HTML
<!-- event is passed to function --> < input (keyup)="onKeyUp($event)"> < p >{{text}}</ p > |
app.component.ts
Javascript
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: