Event Binding in Angular: Definitive Guide with Examples

Read it in 10 Mins

Published
25th Jan, 2023
Views
13,864
Event Binding in Angular: Definitive Guide with Examples

If you've always wanted to learn how to use event binding in Angular, you've come to the right place. This article will discuss Angular's event binding and how to apply it to our Angular project. HubSpot estimates that Google receives 5.6 billion searches every day. Now that we think about it, everything that happens is predicated on user inputs, most notably clicks on the search button. Events are triggered after these actions are completed. With event binding in angular, we can leverage these events and their features. This post will detail event binding's advantages, different kinds of events, how to use it in an Angular project, and other subjects. 

How Does Event Binding Works in Angular?  

It is important to know why we need event binding in the first place. So, let us understand this with an example. When a user views a website, the user engages in various activities like clicking buttons, browsing pages, typing in input fields, and many more. 

Therefore, all these user actions may be referred to as "events", where we use event binding to take some action (send a message, visit another website) when an event is triggered.  

Binding to Events 

In its simplest form, an event is nothing but a listener that listens when there are changes: 

Note, in the above event example, the target event gets bound using ‘(‘and‘)’. An Event is assigned to a statement triggered when a button click action is performed. Based on the HTML element we use, there are various events available to use, such as (keyup), 
(submit) and so on. Angular determines an event target by determining whether the target event's name matches an event attribute of a recognised directive. 

app.component.ts 
public search() { 
    return this.http.get(‘https://my-website.com/search’)  
   }

In the example, we are making an HTTP call to our domain/server to get search results. Like this, we can do much more than just an http call. 

Before we move ahead, it is recommended that you take the angular online training as this will help you learn about angular in a more practical way possible. 

Types of Event Binding in Angular

In Angular, there are two types of events when looked from a broad perspective; 

  1. In-built Events - input, click, keyup, keydown, scroll and other angular events. 
  2. Custom Events - Events we can create on our own within a component to cater to our requirements. 

Binding to Passive Events 

  • Passive events are a new feature introduced in modern browsers, most notably in Chrome 51, that helps to improve scroll performance. 
  • Modern browsers have a threaded scrolling mechanism for smooth functioning of scroll. 
  • Without the passive option, the code in the event handler will always be invoked before the UI thread carries out the scrolling, thereby wrecking the scrolling experience. 

The actions listed below can be taken in order to make an event passive. For instance, in the steps following, we'll make a scroll event passive. 

#Step 1 

Create a file zone-flags.ts under src directory. 

#Step 2 

Add the following line into this file. 

content_copy 

(window as any)['__zone_symbol__PASSIVE_EVENTS'] = ['scroll'];  

#Step 3 

In the src/polyfills.ts file, before importing zone.js, import the newly created zone-flags. 

content_copy 

import './zone-flags';import 'zone.js';    
// Included with Angular CLI.

Look into the web application development course if you haven't already.  

Template Statements have Side Effects. With a few minor exceptions, the syntax of template statements is quite similar to that of JavaScript expressions. Only when the relevant event fires do the statement become active. Therefore, it is important to avoid complex logic in using events and template statements, and keep them short and straightforward.  

Statements cannot use Pipe (|). However, we can chain multiple methods or arguments using the operators ; and , we can include a method and pass an event reference or a template variable reference to execute logic after an event is fired.  

Points to Remember 

  • The associated statement is only executed when the associated event occurs. 
  • Statements should be simple and concise. 
  • We can use ; and , to chain multiple methods. 
  • We cannot use the Pipe operator (|) along with statements. 

To know more about template statements, check here. 

Multiple Event Handlers 

Template statements, as we just discussed, also support multiple handlers for a single event. Let us assume there comes a scenario where you want to have multiple tasks to perform based on a single event. You can add as many handlers as you want separated by ; (semi-colon) in the template statement while using event binding. You can check Multiple Event Handlers in action below: 

For instance, in the above example, first the onAddItem() handler gets triggered, followed by assigning itemName = itemName.value 

Note that the handlers or assignments happen in sequence. 

$event Payload

DOM events have useful information about the event in $event payload. The context of the event, i.e the information in the $event varies according to DOM event. For instance, the event metadata for an input event and a click event are different. We can typecast the event in an angular component, perhaps preventing much of the information from being revealed. Below is an illustration that shows the same thing as we say: 

Example: Before Type Casting 

example.component.ts 
<input (click)="onClick($event)">  <p>{{values}}</p> 
example.component.ts 
onClick(eventany) { 
    // without type cast      
    this.values += event.target.value + ' | '; 
} 

Example: After Type Casting (preferred approach) 

onKey(eventMouseEvent) { 
    // with type info     
    this.values += (event.target as HTMLInputElement).value + ' | '; 
} 

Template Reference Variable  

We generally use variables in an angular component and add our validation and business logic. 

For example; 

app.component.ts 
public title='Some variable in component!!' 

However, if we need to use a variable within the template or view itself, the Template reference variable comes to our rescue. 

Template Reference Variable Applications  

  • To pass value from one part of the template to another part of the template. 
  • For form input validation. 
  • Can be used as reference in component .ts file to run business logic. 

How to Use Template Reference Variable? 

A Template variable can be referred to as variables using “#” in the element, component, or directive you want to use. 

Angular assigns a value to the template variable based on the context. If we declare in a HTML tag, value refers to that HTML element. If we declare it in a component, the value refers to the component instance. 

app.component.html 
<input type="text" #name placeholder="Your name" />  
<button type="button" (click)="submitName(name.value)">Submit Name</button> 

In the above example, we are declaring a variable for an input element within a template and using its value in the submitName handler. Whenever a user clicks the Submit Name button, submitName handler gets fired. 

Key Event Filtering (key.enter) 

Key events can be simply broken down into two words i.e Keys and Events. Keys annotates to physical keyboard keys and Events corresponds to the actions performed with the keys.  

Key events can be used to have more control over the user’s interaction through text-based inputs. 

In Angular, for example, the (key.enter) event binding is triggered when user presses and releases a key. Similar to these, there are other events supported in angular. Let us understand the key.enter with an example; 

Approaches to Event Handling 

In angular, there are various ways to handle events. However, the following approaches are common in use: 

  • $event in the Handler 
  • Template Variable Reference  

1. Using $event Handler 

app.component.html 
<input (keyup.enter)="keyHandler($event)" /> 
app.component.ts 
valuesstring = ''; 
keyHandler(event) { 
    this.values = event.target.value; 
} 

In the above example, we are using a handler with $event passed into it. The event information can be captured in the component and used to get the user input on the click of the enter button. 

This is a convenient approach to using event binding. However, it is not the best practice to pass an entire $event as it can reveal too much information. To address this issue, a template reference can be used. 

2. Using Template Reference Variable 

app.component.html 
<input #name (keyup.enter)="userName = name.value" /> 
app.component.ts   
userNamestring = ''; 

Here, we first declare the template variable in the input element and pass its value in the statement of the (key.enter) event. Also, we are directly mapping the value to a variable (userName) declared in the component. 

So far, we have already discussed built-in events and all the different ways that angular may use them. Let us now examine the custom events in Angular: 

Custom Events with EventEmitter   

Custom events are events that we can create within a component. These events are really useful when you have a nested component structure and want to pass data from one component to another. In order to implement custom events in Angular, you must have a parent-child component structure. 

Consider an example, where we have a Card Component (parent component) and a Card Action Component (child component) and we want to share data from Card Action → Card Component. 

To implement custom event binding, we will be using: 

  1. @Input - A decorator to declare a property in a child component that can receive data from the parent component. 
  2. @Output  - A decorator to declare a property in the child component that signifies data flow to the parent component. Note, that the property declared with the @Output decorator must be an instance of EventEmitter. 
  3. EventEmitter instance - A Class to be used along with @Output directive to emit data using .emit(). 

Child Component (card-actions)

card-actions.component.ts 
import { Component } from '@angular/core'; 
@Component({  
    selector: 'card-actions' 
    templateUrl: './card-actions.component.html' 
    styleUrls: ['./card-actions.component.css'],  
}) 
export class CardActionsComponent { 
    name = 'card-actions'; 
    @Input() namestring; 
    @Output() saveDataEventEmitter<any> = new EventEmitter<any>(); 
    onSaveData(namestring) { 
        // sending value to parent     
        this.saveData.emit(name); 
    } ngOnInit() { 
        // Getting default value from parent     
        console.log(this.name); 
    } 
} 
card-actions.component.html 
<input #userName type="text"/> 
<button type="button" (click)="onSaveData(userName.value)">Save</button> 

Flow in Child Component   

  • We have declared a name variable and have added @Input decorator as prefix that will help to receive data from the parent. 
  • saveData is an EventEmitter instance which emits data whenever a user clicks the save button. The Parent component will only receive if @Output is used as a prefix for the emitter. 

Parent Component (Card)  

card.component.ts 
import { Component } from '@angular/core'; 
@Component({  
    selector: 'app-root' 
    templateUrl: './app.component.html' 
    styleUrls: ['./app.component.css'],  
}) 
 
 
export class AppComponent { 
    nameInParentstring = 'Default Value'; 
    receiveName(namestring) { 
        this.nameInParent = name; 
        console.log('received value in parent'name); 
    } 
} 
 
card.component.html 
<app-card-actions   
      (saveData)="receiveName($event)"              
      [name]="nameInParent">    
</app-card-actions> 

Flow in Parent Component  

  • We are declaring a child component (card-actions) as an HTML Tag. 
  • We have used event binding for our custom event saveData using parentheses () around it. The recieveName handler receives data from the child in $event. 
  • nameInParent string data is passed in child through the name property using property binding 

Quick Notes from the Example   

  • For custom event binding in Angular, parent-child relationships between components are crucial. 
  • It uses @Input, @Output, and EventEmitter for component-to-component communication. 

Conclusion  

We hope you now have a clear understanding of how event binding in Angular may be used in angular in ways to strengthen codes like never before. Do check out KnowledgeHut Angular Online Training program to master in-depth concepts of Event Binding in Angular in the simplest ways possible. 

Profile

Jay Bhanushali

Blog Author

I am a Software Developer who enjoys writing code and solving problems. I write to share my understanding and insights about the topics that interests me and perhaps learn something new throughout this process.

Share This Article
Want to become a sought-after web developer?

Avail your free 1:1 mentorship session.

Select
Your Message (Optional)

Frequently Asked Questions (FAQs)

1What is difference between event and property?

Both property and event are used as one-way data binding in Angular, however property is used when we want to send data (either static or dynamic) from parent to the child component and event is used to fire event (on-click, keyup, any custom event) from child component which can be catched by parent component. 

2What is event handler in Angular?

Event handler can simply be considered as a method or function that handles the event of specific HTML element.

For Eg: 

<input (click)=”onClickName($event)” /> 

In this example, the on Click Name is the event handler that can listen to the target event that is clicked.

Upcoming Web Development Batches & Dates

NameDateFeeKnow more