Demonstration of Click Event in Angular 2

Rajnilari2015
Posted by in Angular 2 category on for Beginner level | Points: 250 | Views : 402 red flag

AngularJS 2 is an open source, MV* Javascript framework developed by Google. It is widely use across the industry to build web applications.In this article, we will demonstrate the button click event in Angular 2 way.


 Download source code for Demonstration of Click Event in Angular 2

Recommendation
Read Demonstration of ngFor in Angular 2 before this article.

Introduction

AngularJS 2 is an open source, MV* Javascript framework developed by Google. It is widely use across the industry to build web applications.In this article, we will demonstrate the button click event in Angular 2 way. The base experimental source for this article is the previous one, so it is highly recommended to read the previous article before this.

Objective

In this article we will demonstrate how to perform the click event for every item/record on the grid and also their total salary.

Using the code

Open app.ts file inside the src folder and write the below code

//our root app component
import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

// Annotation section
@Component({
  selector: 'my-app',
  template: `
    <div style="width: 50%; margin: 0 auto;">     
      <employee-selector></employee-selector>
    </div>
  `,  
})
// Component controller
export class App { 
  constructor() { }
}

// Annotation section
@Component({
  selector: 'employee-selector',
  templateUrl: 'employee-information-apps.html'
})

// Component controller
export class EmployeeInformation {

  
  constructor() {

      this.employees = [{					    
					    "name": "Person 1",
					    "gender":"Male",
					    "photo":"images/1.jpg",
					    "address": "Bangalore",
					    "salary": "30000"
					  }, {					   
					    "name": "Person 2",
					    "gender":"Female",
					    "photo":"images/2.jpg",
					     "address": "Bangalore",
					     "salary": "60000"
					  }, {					   
					     "name": "Person 3",
					     "gender":"Female",
					     "photo":"images/3.jpg",
					   	  "address": "Bangalore",
					   	  "salary": "70000"
					  },
					  {					   
					     "name": "Person 4",
					     "gender":"Male",
					     "photo":"images/4.png",
					      "address": "Bangalore",
					      "salary": "90000"
					  }];					 

  }//end constructor	
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App,EmployeeInformation ],
  bootstrap: [ App ]
})
export class AppModule {}

This is the same as described in the previous post with only one extra field salary added to our employees Json.

Now we need to bind the data to the view. So let's create the below employee-information-apps.html

<h1>
	<b>
		<font color="blue">Employee Details</font>
	</b>
</h1>
	
       <table border="1">
			<tr>
				  <th style="background-color: #4CAF50;">Sl No.</th>
				  <th style="background-color: #4CAF50;">Name</th>	
				  <th style="background-color: #4CAF50;">Photo</th>				 
				  <th style="background-color: #4CAF50;">Gender</th>
				  <th style="background-color: #4CAF50;">Address</th>
				  <th style="background-color: #4CAF50;">Salary</th>
			</tr>

			<tr *ngFor="let e of employees; let i = index">
				    
				  <td><span>{{i + 1}}</span></td>
				  <td><span>{{e.name}}</span></td>	
				  <td><span><img src={{e.photo}} width="100px" height="100px" /></span></td>				 
				  <td><span>{{e.gender}}</span></td>
				  <td><span>{{e.address}}</span></td>
				  <td><span>{{e.salary}}</span></td>

			</tr>				
		</table>

Now open the index.html in Fire Fox and the result at this stage is

Now we need to add the click events. For this we need to change the employee-information-apps.html template as under

<h1>
	<b>
		<font color="blue">Employee Details</font>
	</b>
</h1>
	
       <table border="1">
			<tr>
				  <th style="background-color: #4CAF50;">Sl No.</th>
				  <th style="background-color: #4CAF50;">Name</th>	
				  <th style="background-color: #4CAF50;">Photo</th>				 
				  <th style="background-color: #4CAF50;">Gender</th>
				  <th style="background-color: #4CAF50;">Address</th>
				  <th style="background-color: #4CAF50;">Salary</th>
			</tr>

			<tr *ngFor="let e of employees; let i = index" (click)="getEmployeeRecord(e)">
				    
				  <td><span>{{i + 1}}</span></td>
				  <td><span>{{e.name}}</span></td>	
				  <td><span><img src={{e.photo}} width="100px" height="100px" /></span></td>				 
				  <td><span>{{e.gender}}</span></td>
				  <td><span>{{e.address}}</span></td>
				  <td><span>{{e.salary}}</span></td>

			</tr>				
		</table>

		<button (click)="displayTotalEmployeeSalary()" id="btnTotalEmpSal">Get Total Employee Salary</button>

Angular JS 1 way for click event was ng-Click. Angular 2 does this using (click).

Events in Angular 2 use the parentheses notation in templates, and trigger methods in a component's class. For example, let's say we have the below template

<button (click)="ClickMe()" id="btnClickMe">Click Me</button>

and the component class as under

@Component(...)
class TestComponent {
  ClickMe() {
  alert('I am clicked');
  }
}

As soon as the button is clicked, the ClickMe() method will be invoked and the alert message box will be triggered.

Now let us implement the functions inside the app.ts as under

getEmployeeRecord = (emp) => { 

	alert(	"Name : " + emp.name + 
			" \nGender : " + emp.gender + 
			" \nAddress : " + emp.address +
			" \nSalary : " + emp.salary

		  ); } //end of function getEmployeeRecord

This is the TypeScript's arrow notation way of writing where for every employee record we are displaying their information.

displayTotalEmployeeSalary(){
			
			 var totalSalary = 0;

			 for (let i = 0; i < this.employees.length; i++) {

		    	totalSalary = totalSalary - (-this.employees[i].salary);		    
			}
			alert(" Total Salary of the Employees : " + totalSalary);   	
	} //end of function displayTotalEmployeeSalary

We are looping through the employees array in the Type Script's way to perform the total employee salary calculation.

The complete app.ts code is presented below

//our root app component
import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

// Annotation section
@Component({
  selector: 'my-app',
  template: `
    <div style="width: 50%; margin: 0 auto;">     
      <employee-selector></employee-selector>
    </div>
  `,  
})
// Component controller
export class App { 
  constructor() { }
}

// Annotation section
@Component({
  selector: 'employee-selector',
  templateUrl: 'employee-information-apps.html'
})

// Component controller
export class EmployeeInformation {

  
  constructor() {

      this.employees = [{					    
					    "name": "Person 1",
					    "gender":"Male",
					    "photo":"images/1.jpg",
					    "address": "Bangalore",
					    "salary": "30000"
					  }, {					   
					    "name": "Person 2",
					    "gender":"Female",
					    "photo":"images/2.jpg",
					     "address": "Bangalore",
					     "salary": "60000"
					  }, {					   
					     "name": "Person 3",
					     "gender":"Female",
					     "photo":"images/3.jpg",
					   	  "address": "Bangalore",
					   	  "salary": "70000"
					  },
					  {					   
					     "name": "Person 4",
					     "gender":"Male",
					     "photo":"images/4.png",
					      "address": "Bangalore",
					      "salary": "90000"
					  }];					 

  }//end constructor

	   getEmployeeRecord = (emp) => { 

	   	alert(	"Name : " + emp.name + 
	   			" \nGender : " + emp.gender + 
	   			" \nAddress : " + emp.address +
	   			" \nSalary : " + emp.salary

	   		  ); } //end of function getEmployeeRecord

	  displayTotalEmployeeSalary(){
			
			 var totalSalary = 0;

			 for (let i = 0; i < this.employees.length; i++) {

		    	totalSalary = totalSalary - (-this.employees[i].salary);		    
			}

			/* this.employees.forEach(function(arrayItem){		  
			    totalSalary = totalSalary - (-arrayItem.salary);		    
			});*/
			alert(" Total Salary of the Employees : " + totalSalary);   	
	} //end of function displayTotalEmployeeSalary

}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App,EmployeeInformation ],
  bootstrap: [ App ]
})
export class AppModule {}

Now run the application and click on any employee record to get the below output.

Click on the Get Total Employee Salary button to receive the following output

References

Learn Angular 2

Basic TypeScript

Conclusion

This article covers the Click Event in Angular 2 with an example. Hope this will be helpful. Thanks for reading. Zipped file is attached herewith.

Page copy protected against web site content infringement by Copyscape

About the Author

Rajnilari2015
Full Name: Niladri Biswas (RNA Team)
Member Level: Platinum
Member Status: Member,Microsoft_MVP,MVP
Member Since: 3/17/2015 2:41:06 AM
Country: India
-- Thanks & Regards, RNA Team


Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)