English 中文(简体)
Angular 2 - Handling Events
  • 时间:2024-11-03

Angular 2 - Handpng Events


Previous Page Next Page  

In Angular 2, events such as button cpck 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 handpng. In our example, we will look at displaying a cpck button and a status property. Initially, the status property will be true. When the button is cpcked, 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; 
   cpcked(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 cpcked function which will be called whenever our button is cpcked 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.

<span> 
   {{Status}} 
   <button (cpck) = "cpcked()">Cpck</button> 
</span> 

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 Cpck. We then ensure that the cpck event of the button gets triggered to the cpcked event in our class.

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

Cpck True

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

Cpck False Advertisements