Home >>Angular8 Tutorial >Angular8 Event Binding

Angular8 Event Binding

Event Binding in Angular 8

In Angular 8, event binding is used to manage events created from the DOM, such as clicking the switch, mouse movement etc. As the DOM event happens (e.g. press, shift, keyup), it calls in the function to the defined process. In the following illustration the component's cookBacon) (method is called while clicking on the button:

For example:

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

Event Binding Example

Take a button in the HTML template, and handle this button's click event. To implement event linking, we must use a part method to bind click event of a component.

Now, open the app.component.ts file and use the following code:


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

app.component.html:

Event Binding Example

<button (click)="onSave($event)">Save</button>

Event Bubbling

Event bubbling is used to define an order in which event handlers are named while one entity is nested inside a second element, and all entities have registered a listener for the same event ( i.e., click).

Let's take an example of the above button. I used a div wrapper in part HTML around the button here and div also has a click event handler. When div is clicked, it is just to reveal any message.

Use the following code in app.component.ts file:


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

app.component.html:

Event Bubbling Example

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

No Sidebar ads