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...


Comments

Popular posts from this blog

Spring Boot OpenAI Integration: Step-by-Step Guide

Orchestration-Based Saga Architecture and Spring Boot Microservices Implementation Guide

Spring Boot 3 + Angular 15 + Material - Full Stack CRUD Application Example