Quick Contact


    Event Binding in Angular 8

    Event binding in Angular 8

    Event binding is a data-binding from an element to a component. User actions such as keystrokes, mouse movement, clicks, and touches can be bound to the component property using event binding. In the event binding, the target will be an event name.

    It is one-way data binding and sends information from the view to the component class. It is opposite of property binding. It calls the main method in the component is called when the button is clicked.

    Example

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

    Event Binding Example

    Hold a button in the HTML template and hold the click event of this button. To implement event binding, we will attach click event of a button with a method to the component.

    Firstly, 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);
    	}
    	}
    	

    In app.component.html:

    < h2>E< code>v< /code>ent Binding Example< /h2>

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

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

    Now, we could see that the “Save” button is clicked.

    Event Bubbling

    Event bubbling is used to identify an order in which event handlers are called when one element is nested inside a second element. And both parts have registered a listener for the event (i.e., click).

    We are using a div wrapper on the button in component HTML, and div has also a click event handler. It is only to show some message if the div has been clicked.

    Use the given 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!”);
    }
    }

    app.component.html:
    
    	< h2>Event Bubbling Example< /h2>
    	< !-- Event Bubbling --
    	< div (click)="onDivClick()">
    	< button (click)="onSave($event)">Save< /button>< !-- Event Binding -->
    	< /div>
    	
    Output

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

    Here, we can see that our div message has also occurred. This is due to bubbling where we have specified onDivClick button.

    Copyright 1999- Ducat Creative, All rights reserved.