Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Angular2 event binding

Suggested Videos
Part 11 - Angular attribute binding | Text | Slides
Part 12 - Class binding in angular 2 | Text | Slides
Part 13 - Style binding in angular 2 | Text | Slides

In this video we will discuss Event Binding in Angular with examples.



The following bindings that we have discussed so far in this video series flow data in one direction i.e from a component class property to an HTML element property.
1. Interpolation
2. Property Binding
3. Attribute Binding
4. Class Binding
5. Style Binding



How about flowing data in the opposite direction i.e from an HTML element to a component. When a user performs any action like clicking on a button, hovering over an element, selecting from a dropdownlist, typing in a textbox etc, then the corresponding event for that action is raised. We need to know when user performs these actions. We can use angular event binding to get notified when these events occur.

For example the following 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 we have the template statement. In this case the onClick() method of the component class is called when the click event occurs.
<button (click)="onClick()">Click me</button>

With event binding we can also use the on- prefix alternative as shown below. This is known as the canonical form
<button on-click="onClick()">Click me</button>

Event Binding Example : 

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

@Component({
    selector: 'my-app',
    template: `<button (click)='onClick()' >Click me</button>`
})
export class AppComponent {
    onClick(): void {
        console.log('Button Clicked');
    }
}

Every time we click the button, 'Button Clicked' message is logged to the console. You can see this message under the Console tab, in the browser developer tools.
angular bind event to element

Another Example : Initially when the page loads we want to display only the First Name and Last of Employee. We also want to display "Show Details" button.

angular 2 click event example

When we click "Show Details" button, we want to display "Gender" and "Age" as well. The text on the button should be changed to "Hide Details". When we click "Hide Details" button, "Gender" and "Age" should be hidden and the button text should be changed to "Show Details".

angular 2 click event binding

To achieve this we will make use of event binding in Angular. We will also make use of one of the structural directives "ngIf" in angular.

Code in employee.component.ts : Notice we have introduced "showDetails" boolean property. The default value is false, so when the page first loads, we will have "Gender" and "Age" hidden. We also have a method, toggleDetails(), which toggles the value of showDetails. 

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

@Component({
    selector: 'my-employee',
    templateUrl: 'app/employee/employee.component.html',
    styleUrls: ['app/employee/employee.component.css']
})
export class EmployeeComponent {
    columnSpan: number = 2;
    firstName: string = 'Tom';
    lastName: string = 'Hopkins';
    gender: string = 'Male';
    age: number = 20;
    showDetails: boolean = false;

    toggleDetails(): void {
        this.showDetails = !this.showDetails;
    }
}

Code in employee.component.html :
  • Notice the click event of the button is binded to toggleDetails() method
  • To dynamicall change the text on the button, we are using ternary operator - {{showDetails ? 'Hide' : 'Show'}} Details
  • We used ngIf structural directive on "Gender" 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 videos
  • 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" and "Age" <tr> elements are added to the DOM, else removed
<table>
    <thead>
        <tr>
            <th attr.colspan="{{columnSpan}}">
                Employee 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>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>

Angular 2 tutorial for beginners

9 comments:

  1. Hello Venkat,

    When save the application at that time changes aren't reflating on browser..

    ReplyDelete
    Replies
    1. which browser are you using? all browser consoles have an option of "clear cache" or always refresh from the server, but these only work when you have the developer tools opened on the window. Something like this is always related to old browser cache being used for display.

      Delete
  2. Hello Venkat,
    can you please provide one dropdown example

    ReplyDelete
  3. Tons of thanks for all your tutorials.
    Iam a Java devoloper and Iam working on spring as a fresher , is angular2 helpful for me, should I learn it

    ReplyDelete
  4. Thank you sir,,you made my learning easy

    ReplyDelete
  5. Nice! if the above code won't work add the CommonModule on your AppModule.
    import { CommonModule } from '@angular/common'

    ReplyDelete
  6. Hello Venkat,

    Why we use use * in front of "*ngIf"

    ReplyDelete
    Replies
    1. The * prefix before a directive indicates, it is a structural directive

      Delete
  7. Clear Chache of your browser. The shortcut command is CTRL + SHIFT + DEL.

    ReplyDelete

It would be great if you can help share these free resources