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:
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:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4