Home  >  Angular

Angular 2 Event Binding Example

By Arvind Rai, November 19, 2016
On this page we will provide angular 2 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 using TypeScript.

Software Used

Find the software used in our demo.
1. Angular 2.3.0
2. TypeScript 2.0.10
3. Node.js 4.6.0
4. NPM 3.10.8
5. Firefox 50.1.0

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  

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.

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.

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.

Complete Example using TypeScript


event.component.ts
import {Component} from '@angular/core';
@Component({
    selector: 'event-test',
    templateUrl: 'app/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> 
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 { } 
main.ts
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {AppModule} from './module';
const platform = platformBrowserDynamic();
platform.bootstrapModule(AppModule);  
index.html
<html>
  <head>
    <title>Angular 2 Demo</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="node_modules/core-js/client/shim.min.js"></script>
    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/reflect-metadata/Reflect.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <!-- Configure SystemJS -->
    <script src="systemjs.config.js"></script>
    <script>
      System.import('myApp').catch(function(err){ console.error(err); });
    </script>
  </head>
  <body>
    <event-test>Please Wait...</event-test>
  </body>
</html> 

Run Application

Find the steps to run the example.
1. Install Node.js and NPM in the system if not already installed. Make sure that Node.js version must be 4.x.x or higher and NPM version must be 3.x.x or higher.
2. Download the source code using download link given below in the example.
3. Go to the root folder of the project using command prompt and run npm install command.
4. Now run npm start command.
5. Now run index.html file. Find the print screen of the output.
Angular 2 Event Binding Example

Reference

ANGULAR 2 TEMPLATE SYNTAX:Event binding

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2019 concretepage.com | Privacy Policy | Contact Us