Javatpoint Logo
Javatpoint Logo

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:

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:


Event Binding in Angular 8

app.component.html:


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:


Event Binding in Angular 8

app.component.html:


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

Here, you can see that your div message is also occurred. This is all due to event bubbling where you have specified onDivClick button.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA