Angular 8 Event Binding

To handle the events raised from the DOM like button click, mouse movement, etc event binding is used in Angular 8. The specified method is called by event binding in the component when the DOM event happens (eg. click, change, keyup). The cookBacon() method in this example is called from the component when the button is clicked.

Example 1:

<button (click)="cookBacon()"></button>

Example 2:

  • Open the app.component.ts file.
  • Add the following code in it.

app.component.ts:

import { Component } from '@angular/core';    
@Component({    
  selector: 'app-root',    
  templateUrl: './app.component.html',    
  styleUrls: ['./app.component.css']    
})    
export class AppComponent {      
  onSave($event){    
    console.log("Button is clicked!", $event);    
  }    
}

  • Open the app.component.html file.
  • Add the following code in it.

app.component.html:

<h2> Event Binding</h2>  
<button (click)="onSave($event)">Save</button> <!--Event Binding-->

Explanation:

In the above example, we are handling the click event of the button taken in the HTML template. Here, we are binding the click event of a button with a method of the component to implement event binding.

Output 1:

  • Click on the “Save” button.
  • Open the console to see the result.

Output 2:

The “Save” button is thus clicked.

Event Bubbling:

To define the order in which event handlers are called when one element is nested inside a second element, and both elements have registered a listener for the same event i.e. click, the Event bubbling is used in Angular.

  • Open the app.component.ts file.
  • Add the following code in it.

app.component.ts:

import { Component } from '@angular/core';    
@Component({    
  selector: 'app-root',    
  templateUrl: './app.component.html',    
  styleUrls: ['./app.component.css']    
})    
export class AppComponent {      
  onSave($event){    
    console.log("Button is clicked!", $event);    
  }    
  onDivClick(){    
    console.log("DIV is clicked!");    
  }    
}

  • Open the app.component.html file.
  • Add the following code in it.

app.component.html:

<h2>Event Bubbling</h2>    
<!-- Event Bubbling -->    
<div (click)="onDivClick()">    
  <button (click)="onSave($event)">Save</button> <!-- Event Binding -->    
</div>

Output 1:

  • Click on the “Save” button.
  • Open the console to see the result.

Output 2:

Explanation:

In the above example, a div wrapper is used around the button in component HTML. Here, the div also has a click event handler, that shows some message when clicked. Thus, the div message has also occurred here because of the event bubbling where the onDivClick button is specified.

Please follow and like us:
Content Protection by DMCA.com