Event Binding in Angular 8

In Angular 8, event binding is used to handle the events raised from the DOM like button click, mouse move etc. When the DOM event happens (eg. click, change, keyup), it calls the specified method in the component. In the following example, the cookBacon() method from the component is called when the button is clicked:

For example:

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

Event Binding Example

Let’s take a button in the HTML template and handle the click event of this button. To implement event binding, we will bind click event of a button with a method of the 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("Save button is clicked!", $event);    

  }    

}   
    Event Binding in Angular 8

    app.component.html:

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

    Output:

    Event Binding in Angular 8

    Click on the “Save” button and open console to see result.

    Event Binding in Angular 8

    Now, you can see that the “Save” button is clicked.

    Event Bubbling

    Event bubbling is used to specify an 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).

    Let’s see the above button example. Here, I have used a div wrapper around the button in component HTML and div has also a click event handler. It is only to show some message if div is clicked.

    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 is clicked!", $event);    
    
      }    
    
      onDivClick(){    
    
        console.log("DIV is clicked!");    
    
      }    
    
    }   
      Event Binding in Angular 8

      app.component.html:

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

        Output:

        Event Binding in Angular 8

        Click on the “Save” button and open console to see result.

        Event Binding in Angular 8

        Comments

        Leave a Reply

        Your email address will not be published. Required fields are marked *