Angular 10 - Event Binding

In Angular, event binding is utilized to handle the events raised by the utilizer actions like button click, mouse movement, etc. When the DOM event transpires at an element(e.g. click, key down, etc...) it calls the designated method in the particular component.

Syntax

<button (click)="onShow()">Show</button>

Let us consider an example to understand this better.

Example1:Using click event on the input element.

app.component.html

<h1> 
Knowledgefactory
</h1>
<input (click)="myAction($event)" value="Knowledgefactory">

app.component.ts

import { Component } from '@angular/core';     
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
myAction(event) {
alert(event.toElement.value)
}
}
In the app.component.html file, we have defined a button and added a function to it using the click event.
Upon clicking the button, the control will come to the function myAction and a dialog box will appear.




Example2:Using keyup event on the input element.

app.component.html

<input (keyup)="onKeyUp($event)">   
<p>{{message}}</p>

app.component.ts

import { Component } from '@angular/core';     
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
message = '';
onKeyUp(x) {

// Appending the updated value
// to the variable
this.message += x.target.value + ' + ';
}
}




More...


Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Spring boot video streaming example-HTML5

Spring Boot + Mockito simple application with 100% code coverage

Spring Boot + OpenCSV Export Data to CSV Example

Custom Exception Handling in Quarkus REST API

Registration and Login with Spring Boot + Spring Security + Thymeleaf

DataTable-Pagination example with Spring boot, jQuery and ajax

Spring Webflux File Download - REST API Example

Node JS mini projects with source code - free download

ReactJS, Spring Boot JWT Authentication Example