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

Javascript objects and reference variables

Suggested Videos
Part 43 - Angular optional route parameters | Text | Slides
Part 44 - Angular required route parameter vs optional route parameter | Text | Slides
Part 45 - Angular form reset | Text | Slides

This is continuation to Part 45, please watch Part 45 from Angular CRUD tutorial before proceeding.


The following is the reason the submitted data becomes NULL when the angular form is reset
  1. The "Create Employee Form" is bound to the Employee object.
  2. This same employee object is passed to the save method of the Employee Service.
    this._employeeService.save(this.employee);
  3. When the form is reset, the employee object which is bound to the form is also reset. This happens because of the Angular 2 way data-binding.
  4. As the employee object that is bound to the form, and the employee object that is passed to the save() method are the same, when the form is reset, the bound employee object is reset and as a result, the employee object passed to the save() method is also reset.

To solve this create a new employee object and copy over all the values of the employee object, and then pass the newly created employee object to the save() method.

Notice in the example below, we are using Object.assign() method to copy the employee object property values into a new employee object

saveEmployee(): void {
  const newEmployee: Employee = Object.assign({}, this.employee);
  this._employeeService.save(newEmployee);
  this.createEmployeeForm.reset();
  this._router.navigate(['list']);
}

Regarding reference variables the key point to keep in mind is, object reference variables are pointers to objects, they are not objects themselves.

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.