SPA Using Angular 2, ASP.NET Core 1.1 And Entity Framework Core - Part Two

Introduction

This is the second part of this series. If you didn't read the previous article, then please read that on the following link.

In the first part of this series, we covered the following topics.

  • Setup development environment for Angular 2
  • Understand the structure of application
  • Add Entity Framework in Project
  • Create new pages to see the Employee List.
  • Perform Angular 2 routing.
  • Add Service

In this final part of series, we will cover the following.

  • Add functionality to add a new employee.
  • Show the details of existing employee.
  • Edit details of existing employee.
  • Delete existing employee.
  • Add searching functionality to employee listing page.

Let’s cover all the above points one by one.

Add New Employee

Home page of our application contains “New Employee” option in side menu. On click of this menu item, a new screen will open where we can add a new employee entry.  We will create the following screen to add the details of a new employee.

Employee

You can see that in the add employee page, we have a dropdown for the projects list. So, first of all we need to create an API using which we can get the list of projects. For this, right click on “Controller” folder and add new API controller. Name this controller as “ProjectsController” and paste the following code in it.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using Microsoft.AspNetCore.Http;  
  6. using Microsoft.AspNetCore.Mvc;  
  7. using EMS.Model;  
  8. using Microsoft.EntityFrameworkCore;  
  9.   
  10. namespace EMS.Controllers  
  11. {  
  12.     [Produces("application/json")]  
  13.     [Route("api/Projects")]  
  14.     public class ProjectsController : Controller  
  15.     {  
  16.         private readonly EmployeeContext _context;  
  17.   
  18.         public ProjectsController(EmployeeContext context)  
  19.         {  
  20.             _context = context;  
  21.         }  
  22.         // GET: api/Projects  
  23.         [HttpGet]  
  24.         public async Task<IActionResult> Get()  
  25.         {  
  26.             List<Project> project_ = new List<Project>();  
  27.             var Project = await (from data in _context.Project  
  28.                                  select new  
  29.                                  {  
  30.                                      ProjectId = data.ProjectId,  
  31.                                      ProjectName = data.ProjectName  
  32.                                  }).ToListAsync();  
  33.             Project.ForEach(x =>  
  34.             {  
  35.                 Project pro = new Project();  
  36.                 pro.ProjectId = x.ProjectId;  
  37.                 pro.ProjectName = x.ProjectName;  
  38.                 project_.Add(pro);  
  39.             });  
  40.   
  41.   
  42.             return Json(project_);  
  43.         }  
  44.   
  45.          
  46.          
  47.     }  
  48. }   

In the above code, we created an asynchronous method Get of “GET” type, and in this method, we are getting the list of all projects and return this list in JSON format.

Now, open your “services.ts” file and paste the following code into this. 

  1. getProjectList() {  
  2.         return this.http.get('http://localhost:54273/api/projects');  
  3.     }  

In the above code, we created “getProjectList” method in which we executed the get method of “http” class to get the project list.

Now, open “newEmployee.component.ts” file and paste the following code into this file.

  1. import { Component } from '@angular/core';  
  2. import { EmployeeServcies } from '../../Services/services';  
  3. import { Response } from '@angular/http';  
  4. import { FormGroup, FormControl, Validators } from '@angular/forms';  
  5.   
  6.   
  7. @Component({  
  8.     selector: 'new-employee',  
  9.     templateUrl: './newEmployee.component.html',  
  10.      
  11. })  
  12. export class newEmployeeComponent {  
  13.     public ProjectList = [];  
  14.     public formData: FormGroup;  
  15.     public constructor(private empService: EmployeeServcies) {  
  16.         this.empService.getProjectList()  
  17.             .subscribe(  
  18.             (data: Response) => (this.ProjectList = data.json())  
  19.             );  
  20.   
  21.         this.formData = new FormGroup({  
  22.             'EmployeeName'new FormControl('', [Validators.required]),  
  23.             'Designation'new FormControl('',Validators.required),  
  24.             'Skills'new FormControl('', Validators.required),  
  25.             'Project'new FormControl(0, [Validators.required, this.customValidator])      
  26.         });  
  27.   
  28.     }  
  29.   
  30.     customValidator(control: FormControl): { [s: string]: boolean } {  
  31.         if (control.value == "0") {  
  32.             return { data: true };  
  33.         }  
  34.         else {  
  35.             return null;  
  36.         }  
  37.     }  
  38.   
  39.     submitData() {  
  40.         if (this.formData.valid) {  
  41.             var Obj = {  
  42.                 Designation: this.formData.value.Designation,  
  43.                 EmployeeName: this.formData.value.EmployeeName,  
  44.                 ProjectId: this.formData.value.Project,  
  45.                 Skills: this.formData.value.Skills,  
  46.             };  
  47.             this.empService.postData(Obj).subscribe();  
  48.             alert("Employee Inserted Successfully");  
  49.         }  
  50.           
  51.     }  
  52.   
  53.   
  54. }  

In constructor function, we create an instance of the “EmployeeServcies” class and call the “getProjectList” method to get the list of all projects and in response section, we insert the list of retrieved projects into “ProjectList” object of array type and later, we will bind this list to dropdown that shows the list of projects.

  1. this.formData = new FormGroup({  
  2.             'EmployeeName'new FormControl('', [Validators.required]),  
  3.             'Designation'new FormControl('',Validators.required),  
  4.             'Skills'new FormControl('', Validators.required),  
  5.             'Project'new FormControl(0, [Validators.required, this.customValidator])      
  6.         });  

In the above line of code, we will create a FormGroup and in that, we create four form controls (EmployeeName, Designation, Skills and Project). We will bind the formGroup to the form section that we will create in “html” section. The reason behind using the “formGroup” is that we want to use the data(model) driven approach instead of template driven to create the form section, because using the data(model) driven approach, we can create and apply custom validation easily. You can see that in “Project” FormControl, we implement two validations. The first one is inbuilt validation which is required one and the second validation is “customValidator” that is a custom validation. Given below is the code of this validation.

  1. customValidator(control: FormControl): { [s: string]: boolean } {  
  2.         if (control.value == "0") {  
  3.             return { data: true };  
  4.         }  
  5.         else {  
  6.             return null;  
  7.         }  
  8.     }  

In “customValidator”, we are confirming that the selected value of a control should now be 0. If value of control is 0, then we return “true” as return value and this return value indicates the validation has been spoiled. 

Now, open your “newEmployee.component.html” file and paste the following code into this file.

  1. <style>  
  2.     .hidedata {  
  3.         padding-top:50px;  
  4.     }  
  5. </style>  
  6. <div class="row">  
  7.   
  8.     <div class="col-md-12">  
  9.         <div class="col-md-8 col-lg-offset-4">  
  10.             <h3>Enter Employee Details</h3>  
  11.         </div>  
  12.           
  13.                 <div class="row hidedata" id="hidDiv">  
  14.                     <div class="col-md-6 ">  
  15.                         <form class="form-horizontal" [formGroup]="formData" (ngSubmit)="submitData()">  
  16.                             <div class="form-group">  
  17.                                 <label for="EmployeeName" class="col-sm-4 control-label">Employee Name</label>  
  18.                                 <div class="col-sm-8">  
  19.                                     <input type="text" class="form-control"  
  20.                                      name="EmployeeName" placeholder="Employee Name"  
  21.                                           formControlName="EmployeeName" >  
  22.                                 </div>  
  23.                                 <div *ngIf="!formData.get('EmployeeName').valid && formData.get('EmployeeName').dirty"  
  24.                                      class="col-sm-8 col-sm-offset-4" style="color:red">  
  25.                                   Add Employee Name   
  26.                                 </div>  
  27.                             </div>  
  28.                             <div class="form-group">  
  29.                                 <label for="Designation" class="col-sm-4 control-label">Designation</label>  
  30.                                 <div class="col-sm-8">  
  31.                                     <input type="text" class="form-control"  
  32.                                            name="Designation" placeholder="Designation"  
  33.                                            formControlName="Designation">  
  34.                                 </div>  
  35.                                 <div *ngIf="!formData.get('Designation').valid && formData.get('Designation').dirty"  
  36.                                      class="col-sm-8 col-sm-offset-4" style="color:red">  
  37.                                     Add Employee Designation  
  38.                                 </div>  
  39.                             </div>  
  40.                             <div class="form-group">  
  41.                                 <label for="Skills" class="col-sm-4 control-label">Skills</label>  
  42.                                 <div class="col-sm-8">  
  43.                                     <input type="text" class="form-control"  
  44.                                            name="Skills" placeholder="Employee Skills"  
  45.                                            formControlName="Skills">  
  46.   
  47.                                 </div>  
  48.                                 <div *ngIf="!formData.get('Skills').valid && formData.get('Skills').dirty"  
  49.                                      class="col-sm-8 col-sm-offset-4" style="color:red">  
  50.                                     Add Skills of Employee   
  51.                                 </div>  
  52.                             </div>  
  53.                             <div class="form-group">  
  54.                                 <label for="ProjectId" class="col-sm-4 control-label">Project</label>  
  55.                                 <div class="col-sm-8">  
  56.                                    <select class="form-control" name="Project"  
  57.                                           formControlName="Project" >  
  58.                                        <option value="0">---Select---</option>  
  59.                                        <option *ngFor="let data of ProjectList" value={{data.projectId}}>  
  60.                                            {{data.projectName}}  
  61.                                        </option>  
  62.                                    </select>  
  63.   
  64.                                 </div>  
  65.                                 <div *ngIf="!formData.get('Project').valid && formData.get('Project').dirty"  
  66.                                      class="col-sm-8 col-sm-offset-4" style="color:red">  
  67.                                     Select a Project for Employee  
  68.                                 </div>  
  69.                             </div>  
  70.   
  71.                             <div class="form-group">  
  72.                                 <div class="col-sm-offset-4 col-sm-8">  
  73.                                     <button type="submit" [disabled]="!formData.valid" class="btn btn-info">Submit</button>  
  74.                                 </div>  
  75.                             </div>  
  76.                         </form>  
  77.   
  78.                     </div>  
  79.                 </div>  
  80.                   
  81.   
  82.     </div>  
  83. </div>   

In the above code, we created a form section and add a total of four controls (three textbox and one dropdown) into this form section.

  1. <form class="form-horizontal" [formGroup]="formData" (ngSubmit)="submitData()">  

When you examine the above code, you will get [formGroup]=”formData” line in form tag. The “formGroup” attribute is used to bind a form with “formGroup” object that we created into component section. Benefits of this approach is that when we submit this form we get value of all the control in a single “formGroup” object in key value pair.

  1. <input type="text" class="form-control"  
  2.   
  3.                                      name="EmployeeName" placeholder="Employee Name"  
  4.   
  5.                                           formControlName="EmployeeName" >  

The fromControlName directive Syncs a “FormControl” in an existing “FormGroup” to a form control element by name. In other words, this directive ensures that any values written to the FormControl instance programmatically will be written to the DOM element (model -> view). Conversely, any values written to the DOM element through user input will be reflected in the FormControl instance (view -> model). In above code we syncs the “EmployeeName” form control to the “EmployeeName” element. In the same way we wind all three existing the elements to “form control” of “FormGroup”.

  1. <form class="form-horizontal" [formGroup]="formData" (ngSubmit)="submitData()">  

In form tag, we implemented the “ngSubmit” form event, so when form is submitted, it will call “submitData” method of component section. In “submitData” method, we implement the following code.

  1. submitData() {  
  2.         if (this.formData.valid) {  
  3.             var Obj = {  
  4.                 Designation: this.formData.value.Designation,  
  5.                 EmployeeName: this.formData.value.EmployeeName,  
  6.                 ProjectId: this.formData.value.Project,  
  7.                 Skills: this.formData.value.Skills,  
  8.             };  
  9.             this.empService.postData(Obj).subscribe();  
  10.             alert("Employee Inserted Successfully");  
  11.         }  
  12.           
  13.     }  

In the above code, first of all, we check if the form is in valid state or no. If yes, we get the values from “formData” FormGroup and insert into JSON object and call the “postData” method of “EmloyeeService” and pass the create object(Obj) as parameter.

Now, open your “Servcie”ts” file and paste the following code into this file.

  1. postData(empObj: any) {  
  2.         let headers = new Headers({  
  3.             'Content-Type':  
  4.             'application/json; charset=utf-8'  
  5.         });  
  6.         let options = new RequestOptions({ headers: headers });  
  7.         return this.http.post('http://localhost:54273/api/employee', JSON.stringify(empObj), options);  
  8.     }  

In this code, we call the post method of http inbuilt service. We create a header and pass this header to post method of http service.  We stringify  the “empObj” and pass along with POST request. We are calling the POST method of “Employee” api controller. Now we need to add a “POST” method in our “Employee” API controller.

Add the following code into “Employee” controller.

  1. [HttpPost]  
  2.         public IActionResult AddEmployee([FromBody]Employee empObj)  
  3.         {  
  4.             _context.Employee.Add(empObj);  
  5.             _context.SaveChanges();  
  6.             return Json("OK");  
  7.   
  8.   
  9.         }  

In above lines of code, we created an http post method which takes a parameter of employee type. We fetch out the parameter value from the FormBody of the request and add this employee object to the employee dbcontext and save the changes.

Now, all setups are ready to add the new entry of employee, let’s try to add a new employee.

 Employee

The above screen is showing the validation message. In case we break any validation conditions, then we get the corresponding error message.

Employee

If we don’t spoil any validation and press the submit button, then we get the alert message of “Employee Inserted Successfully”. Now, if you go to the home screen you will find that entry of new employee into list.

Employee

Show Employee Details

In index View, we are display the list of all employees and each employee entry also contains “Detail” button.

Employee

Using this button, we can get all information of an employee. Actually this button is an anchor tag in this anchor tag we use the “routerLink” directive and passing “details” and employee id in URL. For example if we click on “Details” button for the “Raj Kumar” employee whose EmployeeID is 4 then “http://localhost:54273/details/4” URL will generate.

  1. <a [routerLink]="['/details/',empData.employeeId]"  
  2.                            class="btn btn-primary">  
  3.                             Detail  
  4.                         </a>  

We can retrieve the Employee details on  behalf of this Employee id. Now, open “details.component.ts” file and add the following code into this file.

  1. import { Component } from '@angular/core';  
  2. import { EmployeeServcies } from '../../Services/services';  
  3. import { Response } from '@angular/http';  
  4. import { Router, ActivatedRoute, Params } from '@angular/router';  
  5.   
  6. @Component({  
  7.     selector: 'employee-detail',  
  8.     templateUrl: './details.component.html'  
  9. })  
  10. export class DetailsComponent {  
  11.     private EmpId: number;  
  12.     public EmployeeDetails = {};  
  13.     public constructor(private empService: EmployeeServcies, private activatedRoute: ActivatedRoute) {  
  14.         this.activatedRoute.params.subscribe((params: Params) => {  
  15.             this.EmpId = params['id'];  
  16.         });  
  17.   
  18.         this.empService.getEmployeeDetails(this.EmpId)  
  19.             .subscribe((data: Response) => (this.EmployeeDetails["employeeName"] = data.json().employeeName,  
  20.                 this.EmployeeDetails["Designation"] = data.json().designation,  
  21.                 this.EmployeeDetails["ProjectName"] = data.json().projectName,  
  22.                 this.EmployeeDetails["Skills"] = data.json().skills,  
  23.                 this.EmployeeDetails["StartDate"] = data.json().startDate,  
  24.                 this.EmployeeDetails["EndDate"] = data.json().endDate  
  25.                 ));  
  26.          
  27.     }  
  28.   
  29.  }  

In the above code, we create an object of “EmployeeServcies” service in constructor function, we also create an instance of “ActivatedRoute” class, “ActivateRoute” is an observable of the URL segments matched by this route. Here we subscribe this observable and get the value of id parameter that we defined during the routing.

Employee

In the next line of code, we subscribe the “getEmployeeDetails” method of EmployeeService and pass the employee’s id as parameter whose details we want to get.  Following is the code of getEmployeeDetails method and paste this code into your “service.ts” file.

  1. getEmployeeDetails(empId: any) {  
  2.   
  3.         return this.http.get('http://localhost:54273/api/employee/' + empId);  
  4.   
  5.          
  6.     }  

In the above code, we call the get method of Employee API and pass the employee’s id parameter. In case of success, we fetched out the employee details from Response object and inserted these details into “EmployeeDetails” object and bound this object to html template.

Now, open “details.component.html” file and paste the following code into this file.

  1. <h2>This is Detail Component</h2>  
  2.   
  3. <div class="row">  
  4.     <div class="col-md-3"><b>Employee Name</b></div><div class="col-md-3">{{EmployeeDetails.employeeName}}</div>  
  5. </div>  
  6. <div class="row">  
  7.     <div class="col-md-3"><b>Designation</b></div><div class="col-md-3">{{EmployeeDetails.Designation}}</div>  
  8. </div>  
  9.   
  10. <div class="row">  
  11.     <div class="col-md-3"><b>Skills</b></div><div class="col-md-3">{{EmployeeDetails.Skills}}</div>  
  12. </div>  
  13. <div class="row">  
  14.     <div class="col-md-3"><b>ProjectName:</b></div><div class="col-md-3">{{EmployeeDetails.ProjectName}}</div>  
  15. </div>  
  16. <div class="row">  
  17.     <div class="col-md-3"><b>Start Date</b></div><div class="col-md-3">{{EmployeeDetails.StartDate|date: 'yMMMMd'}}</div>  
  18. </div>  
  19. <div class="row">  
  20.     <div class="col-md-3"><b>End Date</b></div><div class="col-md-3">{{EmployeeDetails.EndDate|date: 'yMMMMd'}}</div>  
  21. </div>    

Add the following code into “EmployeeController.cs” file.

  1. [HttpGet("{Empid}")]  
  2.         public async Task<IActionResult> EmployeeDetails(int Empid)  
  3.         {  
  4.              
  5.             var EmpDeatils = await(from emp in _context.Employee  
  6.                                    join pro in _context.Project on emp.ProjectId equals pro.ProjectId  
  7.                                    where emp.EmployeeId==Empid  
  8.                                    select new  
  9.                                    {  
  10.                                        emp.EmployeeId,  
  11.                                        emp.EmployeeName,  
  12.                                        emp.Designation,  
  13.                                        pro.ProjectName,  
  14.                                        emp.Skills,  
  15.                                        pro.ProjectId,  
  16.                                        pro.StartDate,  
  17.                                        pro.EndDate  
  18.   
  19.                                    }  
  20.                           ).FirstAsync();  
  21.   
  22.   
  23.             return Json(EmpDeatils);  
  24.         }  

Here, we create a “GET” type method that takes one parameter of integer type. This parameter holds the id of employee and using this employee id, we get details of any employee and pass this details as JSON data. Following is the output of employee detail page.

Employee

Delete Employee Entry

In Employee listing page, we have an option with each employee entry to delete that employee entry.  We add a “click” event listener on this anchor button and call the “DeleteEmployee” method on click event that take the employee’s Id as parameter.

  1. <a   
  2.                            class="btn btn-danger" (click)="deleteEmployee(empData.employeeId)">  
  3.                             Delete  
  4.                         </a>   

 Add the following lines of code in your “home.components.ts” file.

  1. deleteEmployee(empId: number) {  
  2.         
  3.   
  4.         var status = confirm("Are You want to delete this employee ?");  
  5.         if (status == true) {  
  6.             this.empService.removeEmployeeDetails(empId)  
  7.                 .subscribe((data: Response) => (alert("Employee Deleted Successfully")));  
  8.   
  9.             //Get new list of employee  
  10.             this.empService.getEmployeeList()  
  11.                 .subscribe(  
  12.                 (data: Response) => (this.EmployeeList = data.json())  
  13.                 );  
  14.         }  
  15.   
  16.     }  

When we click on delete button a confirmation box will be open that confirm the deletion of the employee details and if status of confirmation box is “true” then we call the “removeEmployeeDetails” method of EmployeeServcie class and pass the employeeId as parameter. Paste following code into your “service.ts” file.

  1. removeEmployeeDetails(empId: any) {  
  2.         let headers = new Headers({  
  3.             'Content-Type':  
  4.             'application/json; charset=utf-8'  
  5.         });  
  6.         return this.http.delete('http://localhost:54273/api/employee'new RequestOptions({  
  7.             headers: headers,  
  8.             body: empId  
  9.         }));  
  10.   
  11.   
  12.     }  

In above code we call the “delete” method of employee api, so we need to add a “Delete” method into our api that takes the employee’s id as parameter. Now open your “EmployeeControler.cs” file and paste the below lines of code.

  1. [HttpDelete]  
  2.         public IActionResult RemoveEmployeeDetails([FromBody]int empId)  
  3.         {  
  4.             Employee Emp;  
  5.             Emp = _context.Employee.Where(x => x.EmployeeId == empId).First();  
  6.             _context.Employee.Remove(Emp);  
  7.             _context.SaveChanges();  
  8.             return Json("OK");  
  9.         }  

In above code we create a method of “http delete” type that takes an employee’s id as parameter that we are fetching from FormBody and using this employee id we delete the record of that particular employee and send the “OK” as confirmation message.

Let’s try to get the record of  the“Sandeep kumar Jangid” employee when we click on delete button a confirmation box will open.

Employee

If you click on “Ok” button then, you will get “Employee Deleted Successfully” message.

 Employee

After this confirmation message you will find that employee list has been refreshed and the deleted employee doesn’t exist into this list.

Employee

Update Employee Details

In employee listing page we added an edit button for each employee. When we click on this button it will redirect to “Edit Employee” page and we are passing the “EmployeeId” as parameter.

  1. <a [routerLink]="['/edit/',empData.employeeId]"  
  2.                            class="btn btn-success">  
  3.                             Edit  
  4.                         </a>  

Now open “editEmployee.component.ts” file and paste the following code into this file.

  1. import { Component } from '@angular/core';  
  2. import { EmployeeServcies } from '../../Services/services';  
  3. import { Response } from '@angular/http';  
  4. import { Router, ActivatedRoute, Params } from '@angular/router';  
  5. import { FormGroup, FormControl, Validators } from '@angular/forms';  
  6.   
  7. @Component({  
  8.     selector: 'edit-employee',  
  9.     templateUrl: './editEmployee.component.html'  
  10. })  
  11. export class editEmployeeComponent {  
  12.     private EmpId: number;  
  13.     public EmployeeDetails = {};  
  14.     public employeeName: string;  
  15.     public ProjectList = [];  
  16.     public formData: FormGroup;  
  17.   
  18.     public constructor(private empService: EmployeeServcies, private activatedRoute: ActivatedRoute) {  
  19.         this.activatedRoute.params.subscribe((params: Params) => {  
  20.             this.EmpId = params['id'];  
  21.         });  
  22.   
  23.         this.empService.getProjectList()  
  24.             .subscribe(  
  25.             (data: Response) => (this.ProjectList = data.json())  
  26.             );  
  27.   
  28.           
  29.   
  30.   
  31.           
  32.          
  33.         this.formData = new FormGroup({  
  34.             'EmployeeId'new FormControl('', [Validators.required]),  
  35.             'EmployeeName'new FormControl('', [Validators.required]),  
  36.             'Designation'new FormControl('', Validators.required),  
  37.             'Skills'new FormControl('', Validators.required),  
  38.             'Project'new FormControl(0, [Validators.required, this.customValidator])  
  39.         });  
  40. this.empService.getEmployeeDetails(this.EmpId)  
  41.             .subscribe((data: Response) => (  
  42.                 this.formData.patchValue({ EmployeeId: data.json().employeeId }),  
  43.                 this.formData.patchValue({ EmployeeName: data.json().employeeName }),  
  44.                 this.formData.patchValue({ Designation: data.json().designation }),  
  45.                 this.formData.patchValue({ Skills: data.json().skills }),  
  46.                 this.formData.patchValue({ Project: data.json().projectId })  
  47.   
  48.             ));  
  49.   
  50.     }  
  51.   
  52.     customValidator(control: FormControl): { [s: string]: boolean } {  
  53.         if (control.value == "0") {  
  54.             return { data: true };  
  55.         }  
  56.         else {  
  57.             return null;  
  58.         }  
  59.     }  
  60.   
  61.     submitData() {  
  62.         if (this.formData.valid) {  
  63.             var Obj = {  
  64.                 EmployeeId: this.formData.value.EmployeeId,  
  65.                 Designation: this.formData.value.Designation,  
  66.                 EmployeeName: this.formData.value.EmployeeName,  
  67.                 ProjectId: this.formData.value.Project,  
  68.                 Skills: this.formData.value.Skills,  
  69.             };  
  70.             this.empService.editEmployeeData(Obj)  
  71.                 .subscribe((data: Response) => (alert("Employee Updated Successfully")));;  
  72.               
  73.         }  
  74.   
  75.     }  
  76. }  

In constructor function we create an instance of EmployeeServcies for accessing the HTTP method that we created. We also create an instance of ActivatedRoute to get the URL parameter values.

  1. this.activatedRoute.params.subscribe((params: Params) => {  
  2.             this.EmpId = params['id'];  
  3.         });  

In above line of code we fetched out the value of “id” parameter and save thid value to “EmpId” variable.

  1. this.empService.getProjectList()  
  2.             .subscribe(  
  3.             (data: Response) => (this.ProjectList = data.json())  
  4.             );  

We call the getProjectList method of EmployeeService class to get the project list and we use these values to bind the project dropdown list.

  1. this.formData = new FormGroup({  
  2.             'EmployeeId'new FormControl('', [Validators.required]),  
  3.             'EmployeeName'new FormControl('', [Validators.required]),  
  4.             'Designation'new FormControl('', Validators.required),  
  5.             'Skills'new FormControl('', Validators.required),  
  6.             'Project'new FormControl(0, [Validators.required, this.customValidator])  
  7.         });  

In above code we create an FormGroup and create total five FormControl into FormGroup. Here we are going to perform the data(model) binding approach to bind a HTML form as similar as add new employee section.

  1. this.empService.getEmployeeDetails(this.EmpId)  
  2.             .subscribe((data: Response) => (  
  3.                 this.formData.patchValue({ EmployeeId: data.json().employeeId }),  
  4.                 this.formData.patchValue({ EmployeeName: data.json().employeeName }),  
  5.                 this.formData.patchValue({ Designation: data.json().designation }),  
  6.                 this.formData.patchValue({ Skills: data.json().skills }),  
  7.                 this.formData.patchValue({ Project: data.json().projectId })  
  8.   
  9.             ));  

In the above lines of code we call the getEmployeeDetails method of EmployeeService class to get the inserted details of an employee and insert these details into formControl of formData. The  patchValue method of formGroup is used to patch the value of FormControl of a formGroup; in other words pathValue method is used to match the value of FormControl. Here we get the data from “getEmployeeDetails” method and insert these data into FormControl of the formGroup using patchValue method.

  1. customValidator(control: FormControl): { [s: string]: boolean } {  
  2.         if (control.value == "0") {  
  3.             return { data: true };  
  4.         }  
  5.         else {  
  6.             return null;  
  7.         }  
  8.     }  

In the above line of code we create a custom validator to validate the value of any control. It will set the invalid state of formGroup an formControl if the value of control is 0. Now open “editEmployee.component.html” file and paste the following code.

  1. <style>  
  2.     .hidedata {  
  3.         padding-top: 50px;  
  4.     }  
  5. </style>  
  6. <div class="row">  
  7.   
  8.     <div class="col-md-12">  
  9.         <div class="col-md-8 col-lg-offset-4">  
  10.             <h3>Edit Employee Details</h3>  
  11.         </div>  
  12.   
  13.         <div class="row hidedata" id="hidDiv">  
  14.             <div class="col-md-6 ">  
  15.                 <form class="form-horizontal" [formGroup]="formData" (ngSubmit)="submitData()">  
  16.                     <div class="form-group">  
  17.                         <label for="EmployeeName" class="col-sm-4 control-label">Employee Name</label>  
  18.                         <div class="col-sm-8">  
  19.                             <input type="text" class="form-control"  
  20.                                    name="EmployeeName" placeholder="Employee Name"  
  21.                                    formControlName="EmployeeName">  
  22.                         </div>  
  23.                         <div *ngIf="!formData.get('EmployeeName').valid && formData.get('EmployeeName').dirty"  
  24.                              class="col-sm-8 col-sm-offset-4" style="color:red">  
  25.                             Add Employee Name  
  26.                         </div>  
  27.                     </div>  
  28.                     <div class="form-group">  
  29.                         <label for="Designation" class="col-sm-4 control-label">Designation</label>  
  30.                         <div class="col-sm-8">  
  31.                             <input type="text" class="form-control"  
  32.                                    name="Designation" placeholder="Designation"  
  33.                                    formControlName="Designation">  
  34.                         </div>  
  35.                         <div *ngIf="!formData.get('Designation').valid && formData.get('Designation').dirty"  
  36.                              class="col-sm-8 col-sm-offset-4" style="color:red">  
  37.                             Add Employee Designation  
  38.                         </div>  
  39.                     </div>  
  40.                     <div class="form-group">  
  41.                         <label for="Skills" class="col-sm-4 control-label">Skills</label>  
  42.                         <div class="col-sm-8">  
  43.                             <input type="text" class="form-control"  
  44.                                    name="Skills" placeholder="Employee Skills"  
  45.                                    formControlName="Skills">  
  46.   
  47.                         </div>  
  48.                         <div *ngIf="!formData.get('Skills').valid && formData.get('Skills').dirty"  
  49.                              class="col-sm-8 col-sm-offset-4" style="color:red">  
  50.                             Add Skills of Employee  
  51.                         </div>  
  52.                     </div>  
  53.                     <div class="form-group">  
  54.                         <label for="ProjectId" class="col-sm-4 control-label">Project</label>  
  55.                         <div class="col-sm-8">  
  56.                             <select class="form-control" name="Project"  
  57.                                     formControlName="Project">  
  58.                                 <option value="0">---Select---</option>  
  59.                                 <option *ngFor="let data of ProjectList" value={{data.projectId}}>  
  60.                                     {{data.projectName}}  
  61.                                 </option>  
  62.                             </select>  
  63.   
  64.                         </div>  
  65.                         <div *ngIf="!formData.get('Project').valid && formData.get('Project').dirty"  
  66.                              class="col-sm-8 col-sm-offset-4" style="color:red">  
  67.                             Select a Project for Employee  
  68.                         </div>  
  69.                     </div>  
  70.                     <div>  
  71.                         <input type="hidden" id="empId" name="empId" formControlName="EmployeeId" />  
  72.                     </div>  
  73.                     <div class="form-group">  
  74.                         <div class="col-sm-offset-4 col-sm-8">  
  75.                             <button type="submit" [disabled]="!formData.valid" class="btn btn-info">Submit</button>  
  76.                         </div>  
  77.                     </div>  
  78.                 </form>  
  79.   
  80.             </div>  
  81.         </div>  
  82.   
  83.   
  84.     </div>  
  85. </div>   

Here we create an html form and bind this form to formGroup(formData) that we created in out component section. Functionality of this page is similar as the “newEmployee.component.html” page, so I think I don’t need to explain the code of this page. On submit action of the form we call “submitData” method, below is the code of this method.

  1. submitData() {  
  2.         if (this.formData.valid) {  
  3.             var Obj = {  
  4.                 EmployeeId: this.formData.value.EmployeeId,  
  5.                 Designation: this.formData.value.Designation,  
  6.                 EmployeeName: this.formData.value.EmployeeName,  
  7.                 ProjectId: this.formData.value.Project,  
  8.                 Skills: this.formData.value.Skills,  
  9.             };  
  10.             this.empService.editEmployeeData(Obj)  
  11.                 .subscribe((data: Response) => (alert("Employee Updated Successfully")));;  
  12.               
  13.         }  
  14.   
  15.     }  

In the above lines of code we get the value from formData that is FormGroup object and insert into new object(Obj). After that we  call the editEmployeeDatamethod of EmployeeServcie class and passed the previously created object as parameter.

Now open your “service.ts” file and paste tge following code into this file.

  1. editEmployeeData(empObj: any) {  
  2.         let headers = new Headers({  
  3.             'Content-Type':  
  4.             'application/json; charset=utf-8'  
  5.         });  
  6.         let options = new RequestOptions({ headers: headers });  
  7.         return this.http.put('http://localhost:54273/api/employee', JSON.stringify(empObj), options);  
  8.     }  

In the above method we call the “put” method of “Employee” API to update the details of an employee and pass the update information of the employee. Now we need to create a method of “PUT” type in our API class that can get this update information and save this information into database, so open “EmployeeController.cs” file and paste the following code.

  1. [HttpPut]  
  2.         public IActionResult EditEmployee([FromBody]Employee empData)  
  3.         {  
  4.             _context.Entry(empData).State = EntityState.Modified;  
  5.             _context.SaveChanges();  
  6.             return Json("ok");  
  7.         }  

In the above code we create a method of HTTP PUT type, in this method we fetchout the data from the body of the request and save these changes to the database as permanent.  Let’s try to edit the information of “Dhramveer” employee, when you click on edit button the following screen will be open.

Employee

Now make some changes into the existing information as follows.

Employee

When you click on Submit button you will get an alert box of “Employee Updated Successfully” that means details of employee have been updated.

Employee

When you move to home page, you will find that details of employee has been updated.

Employee

Add Search Box

Now we add search functionality in our project, for this we will add a textbox. Actually we are going to add the filtering on Employee list. When we type any value in textbox it will match that text to EmployeeName, Designation and Project field of an employee and return the employee details for whom entered text data matched tat least the field of employee detail.  In Angular 1.x we have the filter for this type of task but in Angular 2 and 4 we don’t have any such type of filter. For this Angular 2 comes with a new concept that is Pipe . Using the pipe we can create our custom filter and implement it whereever we want. Let’s create our custom filter using the Pipe.

For this go to “App” directory and create a new folder and name this folder as “pipes”. Now add a new type script file in this folder and name this file as “search.ts” and paste the following code into this file.

  1. import {  Pipe,PipeTransform } from '@angular/core';  
  2.   
  3. @Pipe({  
  4.     name: 'searchFilter'  
  5. })  
  6.   
  7. export class filterSearch implements PipeTransform {  
  8.     transform(value: any, args: string): any {  
  9.         if (args == null || args == undefined) {  
  10.             return value;  
  11.         }  
  12.         else {  
  13.             let filter = args.toLocaleLowerCase();  
  14.             return filter ? value.filter(employee => (employee.employeeName.toLocaleLowerCase().indexOf(filter) != -1)  
  15.                 || (employee.designation.toLocaleLowerCase().indexOf(filter) != -1)  
  16.                 || (employee.project.toLocaleLowerCase().indexOf(filter) != -1)  
  17.                 ) : value;   
  18.         }  
  19.     }  
  20. }  

In the above lines of code we define the “@Pipe” meta data that converts this class into a pipe object. The “filterSearch” class inherits the “PipeTransform” interface and we implement the “transform” method of interface into our “filterSearch” class. This method actually takes two parameters. First parameter contains the list data on which we will perform the filtering and  second parameter contains the filter criteria. In above code we return the Employee details if any field(emloyeeName, designation and project) of employee contains the text of filter criteria.

After creating the Pipe now we need to register this pipe in “App.modules.ts” file so register this pipe in app.modules.ts .

Employee

Now our pipe is ready and we have registered this pipe in “app.modules.ts”, last step is remaining to use this pipe in our code. Open your “home.component.html” file and replace the content of this page with following content.    

  1. <div class="row">  
  2.     <div class="col-md-12">  
  3.         <h3>Employee List</h3>  
  4.         <br />  
  5.          
  6.     </div>  
  7.     <div class="col-md-12">  
  8.           
  9.             <div class="form-actions no-color">  
  10.                   
  11.                 <div>  
  12.                     <span style="font-weight:bold;font-size:20px">Search:</span>  
  13.                     <input type="text" name="searchdata"  #search (keyup)="0"/>  
  14.                      
  15.                       
  16.                 </div>  
  17.             </div>  
  18.        <br />  
  19.     </div>  
  20. </div>  
  21. <div class="row">  
  22.     <div class="table-responsive">  
  23.         <table class="table">  
  24.             <thead>  
  25.                 <tr>  
  26.                     <th>  
  27.                           
  28.                         S.No.  
  29.                     </th>  
  30.                     <th>  
  31.                         EmployeeName  
  32.                     </th>  
  33.                     <th>  
  34.                         Designation  
  35.                     </th>  
  36.                     <th>  
  37.                         Project  
  38.                     </th>  
  39.                     <th>  
  40.                         Action  
  41.                     </th>  
  42.                 </tr>  
  43.             </thead>  
  44.             <tbody>  
  45.                   
  46.                 <tr *ngFor="let empData of EmployeeList | searchFilter:search.value  ; let i = index; trackBy: employeeId">  
  47.                     <td>  
  48.                         {{i+1}}  
  49.                     </td>  
  50.                     <td>  
  51.                         {{empData.employeeName}}  
  52.                     </td>  
  53.                     <td>  
  54.                        {{empData.designation}}  
  55.                     </td>  
  56.                     <td>  
  57.                        {{empData.project}}  
  58.                     </td>  
  59.                     <td>  
  60.   
  61.                         <a [routerLink]="['/details/',empData.employeeId]"  
  62.                            class="btn btn-primary">  
  63.                             Detail  
  64.                         </a>  
  65.                         <a [routerLink]="['/edit/',empData.employeeId]"  
  66.                            class="btn btn-success">  
  67.                             Edit  
  68.                         </a>  
  69.                         <a   
  70.                            class="btn btn-danger" (click)="deleteEmployee(empData.employeeId)">  
  71.                             Delete  
  72.                         </a>  
  73.                     </td>  
  74.                 </tr>  
  75.                   
  76.         </table>  
  77.     </div>  
  78. </div>   

In above code me make only to changes first one is add a text box and bind local template variable with this textbox (#search).

  1. <div class="col-md-12">  
  2.           
  3.             <div class="form-actions no-color">  
  4.                   
  5.                 <div>  
  6.                     <span style="font-weight:bold;font-size:20px">Search:</span>  
  7.                     <input type="text" name="searchdata"  #search (keyup)="0"/>  
  8.                      
  9.                       
  10.                 </div>  
  11.             </div>  
  12.        <br />  
  13.     </div>  

The second change in that we implement the pipe that we created on employee list and pass the value of local template variable (search) as filtering criteria.

<tr *ngFor="let empData of EmployeeList | searchFilter:search.value  ; let i = index; trackBy: employeeId">

After making all the changes now our screen will look like below.

Employee

Now if we enter any text into textbox it will filter the employee list and only show the employee details who match the filtering criteria.

Employee

Summary

This is the second and last part of this series. I hope you liked this. During this series, we learned how to start Angular 2 with .NET Core. We implemented the Code-First approach of the Entity Framework and setup the database connection. We performed the CRUD operations that are basic learning steps of any technology. We learned how to create and implement the services in Angular 2. We also learned about the Pipe and created our custom pipe to implement the filter functionality in our project. If you have any query regarding this series or Angular 2 and .Net Core, then write in comment section. If you want to download this project, go to this github repository.

Up Next
    Ebook Download
    View all
    Learn
    View all