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

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete