Angular Event Binding

Angular Event Binding

In this article, I am going to discuss the Angular Event Binding with examples. As of now, the bindings that we have discussed in this article series flow data in one direction i.e. from a component class property to an HTML element property. Please read the following articles before proceeding to this article.

  1. Angular Interpolation
  2. Property Binding
  3. Attribute Binding
  4. Class Binding
  5. Style Binding

Let’s now discuss how to flow the data in the opposite direction i.e. from an HTML element to a component

When a user performs an action like clicking on a button, selecting from a dropdown list, hovering over an element, typing in a textbox etc., then the corresponding event for that action is raised. We can use the angular event binding to get notified when these events occur. 

The following example is the syntax for binding to the click event of a button. Within parentheses on the left of the equal sign, we have the target event, (click) in this case and on the right-hand side we have the template statement. In this case, the onClick() method of the component class is called when the click event occurs

Angular Event Binding

With event binding, we can also use the on- prefix alternative as shown below. This is known as the canonical form

Angular Event Binding

Event Binding Example:  

Modify the App.Component.ts file as shown below

import { Component } from '@angular/core';

@Component({
    selector: 'my-app',
    template: `<div>
                    <button (click)="onClick()">Click me</button>
              </div>`
})

export class AppComponent {
    onClick(): void {
        console.log('Button is Clicked');
    }
}

Run the application and open the browser developer tools by pressing the F12 key. Notice every time you click the button, ‘Button is Clicked’ message is logged to the console. You can see this message under the Console tab as shown in the below image. 

Angular Event BindingAnother Example: 

When the page loads for the first time, we want to display only the First Name and Last Name of the Employee. We also display the “Show Details” button as shown in the below image. 

Angular Event BindingWhen the user clicks on the “Show Details” button, we want to display the “Gender“, “Age“, “Mobile”, and “Branch” as well. The text on the button should be changed to “Hide Details” and when the user clicks on the “Hide Details” button, then the “Gender“, “Age“, “Mobile”, and “Branch should be hidden and the button text should be changed to “Show Details”

Angular Event Binding  We can achieve this with the help of event binding in Angular. Here we will make use of one of the structural directives “ngIf” in angular.

The code in Student.Component.ts file:

Notice we have introduced “ShowDetails” boolean property. The default value is false, so when the page loads for the first time, we will have “Gender”, “Age”, “Mobile”, and “Branch” hidden. We also have a method, ToggleDetails(), which will toggle the value of ShowDetails. 

import { Component } from '@angular/core';

@Component({
    selector: 'my-student',
    templateUrl: 'app/Student/StudentComponent.html',
    styleUrls: ['app/Student/studentcomponent.css']
})

export class StudentComponent {
    ColumnSpan: number = 2;
    FirstName: string = 'Pranaya';
    LastName: string = 'Rout';
    Branch: string = 'CSE';
    Mobile: number = 9876543210
    Gender: string = 'Male';
    Age: number = 20;
    
    ShowDetails: boolean = false;

    ToggleDetails(): void {
        this.ShowDetails = !this.ShowDetails;
    }
}
The code in StudentComponent.html:

Notice the click event of the button element is bounded to ToggleDetails() method. To dynamically change the text on the button, we are using a ternary operator – {{ShowDetails ? ‘Hide’ : ‘Show’}} Details

We used ngIf structural directive on “Gender”, “Branch”, “Mobile” and “Age” <tr> elements 

The * prefix before a directive indicates, it is a structural directive. Besides ngIf, there are other structural directives which we will discuss in our upcoming articles.

The ngIf directive conditionally adds or removes content from the DOM based on whether or not an expression is true or false. If “ShowDetails” is true, “Gender”, “Branch”, “Mobile” and “Age” <tr> elements are added to the DOM, else removed

<table>
    <thead>
        <tr>
            <th attr.colspan="{{ColumnSpan}}">
                Student Details
            </th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>First Name</td>
            <td>{{FirstName}}</td>
        </tr>
        <tr>
            <td>Last Name</td>
            <td>{{LastName}}</td>
        </tr>
        <tr *ngIf='ShowDetails'>
            <td>Branch</td>
            <td>{{Branch}}</td>
        </tr>
        <tr *ngIf='ShowDetails'>
            <td>Mobile</td>
            <td>{{Mobile}}</td>
        </tr>
        <tr *ngIf='ShowDetails'>
            <td>Gender</td>
            <td>{{Gender}}</td>
        </tr>
        <tr *ngIf='ShowDetails'>
            <td>Age</td>
            <td>{{Age}}</td>
        </tr>
    </tbody>
</table>
<br/>
<button (click)='ToggleDetails()'>
    {{ShowDetails ? 'Hide' : 'Show'}} Details
</button>

Then modify the root component i.e. App.Component.ts as shown below.

Angular Event Binding

Now run the application and you will see everything is working as expected. In the next article, I will discuss two-way data binding in angular with examples.

SUMMARY:

In this article, I try to explain Angular Event Binding with some examples. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

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