Angular Event Binding Example

By Arvind Rai, February 10, 2024
On this page we will provide Angular event binding example. Event binding is a data binding from an element to a component. Data obtained from user actions such as keystrokes, mouse movements, clicks, and touches can be bound to component property using event binding. In the event binding, target will be an event name. Target event is enclosed within parenthesis ( ) or can be used with canonical form using prefix on- to perform event binding. Target event is written to the left side of equal sign. Target events can be click, change, mouseover, mouseout, keydown, keyup etc. In angular framework we can alias our event name as well as we can create custom events. To access current changes by user, we use event object $event. It will be DOM event object if target event is a native DOM element event. It has properties as target and target.value. Event binding using parenthesis ( ) is achieved as follows.
<button (click)="isValid=true">True</button>  
And event binding using on- keyword is achieved as follows.
<button on-click="isValid=true">True</button>  
Call component method on event binding.
<input (change) = "changeText($event.target.value)">  
Here we will provide complete example of event binding step-by-step.

1. Input Event Binding

input event is a DOM event which is fired synchronously when the value of <input> or <textarea> element is changed. Here we will bind the component property with input event. We will use event object $event to get the current value entered by user. For the example find a component property.
msg1 = 'Hello World';  
For the initial value of our <input> element we are using property binding and assigning component property value. For event binding we need to enclose event name by parenthesis as (input) or by using on- keyword as on-input. Now find input event binding using ( ).
<input [value]="msg1" (input)="msg1=$event.target.value">  
We can also use on- keyword as follows.
<input [value]="msg1"  on-input="msg1=$event.target.value">  
Achieve same goal by calling a component method using event binding. Create a method in component.
setMsg(data:string) {
    this.msg1 = data;
} 
Use input event to call the method.
<input [value]="msg1" (input)="setMsg($event.target.value)"> 
Here we are passing the current input data entered by user. If we print the message as
{{msg1}}  
Then we will observe that whenever we write any text in <input> element, at the same time value of msg1 will also be changed. Here $event gives the current value entered by user. We access it by using
$event.target.value
In our code we are assigning its value to msg1 as
msg1=$event.target.value  

2. Click Event Binding

Here we will understand event binding using click event. For the demo we are creating two buttons. We have initialized a component property as
isValid = true;  
Now find the event binding using <button> element as an example.
<button (click)="isValid=true">True</button>
<button (click)="isValid=false">False</button>  
When we click True button, the component property isValid will be assigned with value true and when we click False button then isValid will be assigned with value false. If we are using isValid property in our code anywhere else, accordingly there will be will be change in DOM. For the example we are using it with ngIf as follows.
<p *ngIf="isValid">
	Data is valid.
</p>
<p *ngIf="!isValid">
        Data is not valid.
</p>  
On the click of True button, the first ngIf will run and on the click of False button second ngIf will run.

3. KeyDown and KeyUp Event Binding

Here we will discuss event binding using keydown and keyup event using <input> element. For the demo we are using parenthesis ( ) as well as on- keyword.
<input on-keydown="msg2='Key down'" (keyup)="msg2='Key Up'">  
Here msg2 is a component property and if we print it as
{{msg2}}  
Then on key down we will get message Key down and on key up we will get message Key Up.

4. Change Event Binding

Here we will discuss change event binding using <input> element. On value change we will call a method which we have defined in our component as follows.
changeText(mytext:string) {
     this.msg3 = mytext;
}	 
Now find the <input> element which is using change event binding.
Using parenthesis ( ).
<input (change) = "changeText($event.target.value)">  
Using on- keyword.
<input on-change = "changeText($event.target.value)">  
For the demo we are printing data using innerHTML in <p> element as follows.
<p [innerHTML] = "msg3"> </p>  
Now use interpolation.
<p> {{msg3}} </p> 
When user changes text value then after value change completion, changeText() method will be called and current user input value will be passed to the method that will be assigned to a component property msg3. And hence we will observe value change within <p> element for every value change in <input> element.

5. Complete Example

event.component.ts
import {Component} from '@angular/core';
@Component({
    selector: 'app-root',
    templateUrl: './event.component.html'
})
export class EventComponent {
        isValid = true;
	msg1 = 'Hello World';	
	msg2 = '';
	msg3 = '';
	setMsg(data:string) {
	    this.msg1 = data;
	}
	changeText(mytext:string) {
	    this.msg3 = mytext;
        }	
}   
event.component.html
<b>Input Event Binding </b><br/><br/>
<input [value]="msg1" (input)="msg1=$event.target.value">

<input [value]="msg1" (input)="setMsg($event.target.value)">

{{msg1}}

<br/><br/><b>Click Event Binding </b><br/><br/>
<button (click)="isValid=true">True</button>
<button (click)="isValid=false">False</button>
<p *ngIf="isValid">
	Data is valid.
</p>
<p *ngIf="!isValid">
	Data is not valid.
</p>

<br/><br/><b>Keydown and Keyup Event Binding </b><br/><br/>
<input on-keydown="msg2='Key down'" (keyup)="msg2='Key Up'" >
{{msg2}}

<br/><br/><b>Change Event Binding </b><br/><br/>
<input on-change="changeText($event.target.value)">
<p [innerHTML] = "msg3"> </p> 
app.module.ts
import {NgModule}        from '@angular/core';
import {BrowserModule}   from '@angular/platform-browser';
import {EventComponent}  from './event.component';
@NgModule({
  imports:      [BrowserModule],
  declarations: [EventComponent],
  bootstrap:    [EventComponent]
})
export class AppModule { } 
Find the print-screen of the output.
Angular Event Binding Example

6. Reference

Angular Template syntax

7. Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI







©2024 concretepage.com | Privacy Policy | Contact Us