Event Binding

  • Create a new angular project first using angular CLI.
  • Change the contents of app.component.html file as per below
<h2>{{msg}}</h2>
<button (click)="onButtonClickFunction()" >Click me</button>
  • Make changes to the app.component.ts file as below
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'EventBindingDemo';
  msg : string = 'Button is not yet clicked';
  onButtonClickFunction(){
    this.msg = 'Button has been clicked';
  }
}

Save the changes and run the application on server and you will see something like this on the screen

Before button click

After button click

After button click
  • Now lets analyze how it worked, first we need to see the app.component.html file
  • In above code we can see (click) which is a event, specifically an angular event (Note : We represent event binding in angular using round brackets)
  • On the event (click) a method of its corresponing ts file is called which is onButtonClickFunction() and the code inside it is executed.
  • Below are the list of some events present in angular
(focus)="myMethod()"  
(blur)="myMethod()"   

(submit)="myMethod()" 

(scroll)="myMethod()"

(cut)="myMethod()"
(copy)="myMethod()"
(paste)="myMethod()"

(keydown)="myMethod()"
(keypress)="myMethod()"
(keyup)="myMethod()"

(mouseenter)="myMethod()"
(mousedown)="myMethod()"
(mouseup)="myMethod()"

(click)="myMethod()"
(dblclick)="myMethod()"

(drag)="myMethod()"
(dragover)="myMethod()"
(drop)="myMethod()"

Passing Data from HTML to TS/JS file using event binding.

  • For this example we will create a new angular project using angular CLI
  • We edit the app.component.html file as below
<p>Enter the text below</p>
<input type="text" (input)="onTextInput($event)"/>
<p>The text entered in the above textbox is : </p><br/>
{{textMsg}}

And we edit app.component.ts file as below

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  textMsg : string;
  onTextInput(event : Event){
    this.textMsg = (event.target as HTMLInputElement).value;
  }
}

The output appears to be like below :

In the above output, as we type content in the text box, we same text appears to be in the text below .

  • This happens because we pass the $event to our method.
  • In that method we save into variables which is displayed into the template/html using string interpolation.

Leave a Comment