Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

Create operation in angular

Suggested Videos
Part 28 - Angular trigger validation manually | Text | Slides
Part 29 - Angular form group validation | Text | Slides
Part 30 - Angular 5 services tutorial | Text | Slides

In this video we will discuss creating a new employee using the Create Employee form. This is continuation to Part 30. Please watch Part 30 from Angular CRUD tutorial before proceeding.


Modify EmployeeService to include save() method

Include the following save() method in EmployeeService in employee.service.ts file. At the moment, the save() method just pushes the employee object into the employees array. In a later video, we will discuss saving the employee to a database table by calling a web service over http.


save(employee: Employee) {
    this.listEmployees.push(employee);
}

Injecting and using EmployeeService in CreateEmployeeComponent

Make the following changes in create-employee.component.ts file

Include the following import statement to import EmployeeService
import { EmployeeService } from './employee.service';

Also, import Angular Router service. We will use this service's navigate() method to redirect the user to the employee list page after saving the employee.
import { Router } from '@angular/router';

Inject EmployeeService and Router service into the CreateEmployeeComponent using it's constructor.
constructor(private _employeeService: EmployeeService,
            private _router: Router)

Modify saveEmployee() method as shown below. Notice the saveEmployee() method calls the EmployeeService save() method passing it the employee object we want to save. Wait a minute, the employee object has all it's properties initialised to NULL. How do we get the values from the controls on the form to the properties of this employee object.

Well, we do not have to write any code to keep employee object properties and the form control values in sync. Angular's two way data-binding does that for us automatically.

Finally, we redirect the user to the "list" route using the navigate() method of the angular Router service.

saveEmployee(): void {
  this._employeeService.save(this.employee);
  this._router.navigate(['list']);
}

Also, modify the call to saveEmployee() method in create-employee.component.html file as shown below. Notice we removed the employee object that was being passed as a paramter.

<form #employeeForm="ngForm" (ngSubmit)="saveEmployee()">

At the moment, there is a small issue with data on the employee list page. Notice for the existing employees the department name is displayed where as for the new employeees department id is displayed. We will discuss how to fix this in our next video.

angular crud tutorial

No comments:

Post a Comment

If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.