Event binding in Angular

Event Binding : Meaning

An action performed by the user on the HTML page is an event, typically using mouse or a keyboard. A user can type in a text box, click on a checkbox, right click on the page. All these are considered as events. Enabling the HTML elements to respond to user actions is called Event handling. In order to perform some specific actions when particular event occurs, an event handler function is required.
Putting all these together, namely, adding support over an HTML element for a particular event and providing a handler function to perform action on that event is called Event Binding. In simpler words, when an element contains support to handle an event, it is called event binding. Common events are click, key up, mouse movement.

Event binding makes a template more dynamic by responding to user actions.

Event Binding : How?

Angular components support event binding. It is done by declaring the type of event which needs to be handled, the name of function which shall handle the event and by defining the body of this function. Declaring the event type and the name of handler function is done in the HTML template while the definition of handler function is provided in the component class.  Let’s look the example.
Suppose HTML template of a component is

<div>
    <span> Enter email</span>
    <input type=”text” />
   <input type=”checkbox” />
</div>

Say we want to perform an action when checkbox is clicked and an action when the user types something in the text box and moves to another element. Thus, the event on the checkbox will be click and the event on the text box will be focusout.

Event Binding : Syntax

Event name enclosed within parenthesis followed by the name of the handler function is written on the HTML element which should have the event. Thus, syntax is 

(eventname) = “handlerFunction()”

Example, click and focusout events, as discussed above, will be applied over respective elements in HTML template as

<div>
    <span> Enter email</span>
    <input type=”text” (focusout) = “focusoutHandler() “/>
   <input type=”checkbox” (click) = “handleClick()” />
</div>

Component class for the HTML template will contain the definition of these handler methods as

export class CodippaComponent {
      
            private focusoutHandler() {
                 console.log(“Focus lost”);
            }
            private handleClick() {
                 console.log(“Checkbox clicked”);
            }
}

Accessing Event Object

Each type of event has an object which contains useful information about the event. Often it is necessary to gain access to the event object. Example, when processing mouse events, it is required to know the coordinates of mouse movement. This can be done by providing the event object when declaring the handler function in the HTML template as

<div>
    <span> Enter email</span>
    <input type=”text” (focusout) = “focusoutHandler($event) “/>
   <input type=”checkbox” (click) = “handleClick($event)” />
</div>

Handler function in the component should also be modified to receive the event object as

export class CodippaComponent {
      
            private focusoutHandler(event) {
                 console.log(e);
            }           
            private handleClick() {
                 console.log(e.target);
            }
}

$event is a built-in angular object which contains the event information inside it. If instead of $event, you write event or e or anything else, then the argument value inside handler function will be undefined. However, in the handler function, the argument name can be anything.

event.target represents the element which raised the event.

Though $event object provides information about the event which occurred but passing it around is not considered a good practice since it reveals more information about the HTML template element more than what is required to the component class. This breaks the separation of concerns principle between the template and its component.

Event Propagation or Event Bubbling

In an HTML template or DOM, elements are usually arranged in a hierarchy. That is, element A would be inside element B which would be inside another element C and so on. If an event takes place at a child element then it moves up to the entire DOM hierarchy until all the parent elements are covered or the event is stopped by a parent element or by the source element itself. This is called Event Propagation or Event Bubbling. Example,

<div>
    <div (click) = “handleParentClick()” />
         <input type=”checkbox” (click) = “handleClick()” />
   </div>

</div>

Corresponding component class is

export class CodippaComponent {
      
         private handleParentClick() {
              console.log(“Parent clicked”);
         }           
         private handleClick() {
               console.log(“Checkbox clicked”);
         }
}

Now, if you click on the checkbox, here is what gets printed

Child clicked
Parent clicked

This is because when the child was clicked, its handler method gets called. Now the click event bubbles up the DOM, finds a click event handler at the parent and calls its handler function. If there are some more click event handlers up the DOM, then they will also be called.

Event propagation occurs every time the event occurs but a handler function for a parent will be automatically called only when it is handling the same event which occurred. Example, if in the above example, the event handler function of parent would have been for some event other than click, then it would not have been called.

How to stop Event Bubbling

If you have parent elements handling the same event as the child and you don’t want their handler functions to be called, then you need to stop the event from bubbling up the child. This is done by calling stopPropagation function on the event object. Thus, the event handler function of the child will be modified to

   private handleClick(event) {
      event.stopPropagation();     
      console.log(“Checkbox clicked”);
   }

This will stop the event from chaining upwards the DOM tree.

Also, remember that Event Bubbling is an HTML DOM phenomenon and has nothing to do with Angular. It will also occur in non-angular applications in the same manner.

A bit on quality…

Extract 2 minutes to ask yourself a few questions about this post such as

  • How did you find this post?
  • Could there be anything else which could have been added?
  • Was there something which was unnecessary?
  • There were sufficient examples?

Feel free to write their answers in the comment section below and Keep visiting!!!

Leave a Reply