Handling events in Angular 2

In Angular 2, events such as button click or any other sort of events can also be handled very easily. The events get triggered from the html page and are sent across to Angular JS class for further processing.

Let’s look at an example of how we can achieve event handling. In our example, we will look at displaying a click button and a status property. Initially, the status property will be true. When the button is clicked, the status property will then become false.

Step 1 − Change the code of the app.component.ts file to the following.

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

@Component ({ 
   selector: 'my-app', 
   templateUrl: 'app/app.component.html' 
}) 

export class AppComponent { 
   Status: boolean = true; 
   clicked(event) { 
      this.Status = false; 
   } 
}

Following points need to be noted about the above code.

  • We are defining a variable called status of the type Boolean which is initially true.
  • Next, we are defining the clicked function which will be called whenever our button is clicked on our html page. In the function, we change the value of the Status property from true to false.

Step 2 − Make the following changes to the app/app.component.html file, which is the template file.

<div> 
   {{Status}} 
   <button (click) = "clicked()">Click</button> 
</div> 

Following points need to be noted about the above code.

  • We are first just displaying the value of the Status property of our class.
  • Then are defining the button html tag with the value of Click. We then ensure that the click event of the button gets triggered to the clicked event in our class.

Step 3 − Save all the code changes and refresh the browser, you will get the following output.

Step 4 − Click the Click button, you will get the following output.


To view or add a comment, sign in

More articles by Mayank Attrey

  • Typescript

    Typescript and JavaScript features What is JavaScript? JavaScript is a scripting language which helps you create…

  • Test Your ASP.NET Core Web API With Swagger

    Introduction Testing of Web APIs is always a challenge because it exposes the end-point rather than the UI. Testing…

    1 Comment
  • Microservices

    Microservices The term microservices portrays a software development style that has grown from contemporary trends to…

  • BankEnd WEBAPI with C#

    BankEnd WEBAPI with C# Prerequisites First of all, as we are working with C#, you need to use Microsoft Visual Studio…

    1 Comment
  • One Step To Understand Relationship Of Primary Key And Non-Clustered Indexes.

    Keys and indexes are key fundamental concepts of any RDBMS and play very crucial rule to design good and efficient…

    1 Comment

Explore content categories