Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Angular reactive forms put example

Suggested Videos
Part 26 - RxJS operators in angular services | Text | Slides
Part 27 - Angular reactive forms edit example | Text | Slides
Part 28 - Angular populate formarray | Text | Slides

In this video we will discuss harvesting data from a reactive form and issuing a PUT request to the REST API so the data is updated on the server.


At the component class level, include a property of type IEmployee. We will use this property to hold the employee data loaded from the server for editing.

employee: IEmployee;


Modify getEmployee(id: number) method to store the employee object returned by the REST API

getEmployee(id: number) {
  this.employeeService.getEmployee(id)
    .subscribe(
      (employee: IEmployee) => {
        // Store the employee object returned by the
        // REST API in the employee property
        this.employee = employee;
        this.editEmployee(employee);
      },
      (err: any) => console.log(err)
    );
}

Modify onSubmit() method as shown below.

onSubmit(): void {
  this.mapFormValuesToEmployeeModel();
  this.employeeService.updateEmployee(this.employee).subscribe(
    () => this.router.navigate(['list']),
    (err: any) => console.log(err)
  );
}

Also include the following mapFormValuesToEmployeeModel() method

mapFormValuesToEmployeeModel() {
  this.employee.fullName = this.employeeForm.value.fullName;
  this.employee.contactPreference = this.employeeForm.value.contactPreference;
  this.employee.email = this.employeeForm.value.emailGroup.email;
  this.employee.phone = this.employeeForm.value.phone;
  this.employee.skills = this.employeeForm.value.skills;
}

Code explanation : 

In the view template we have ngSubmit event bound to onSubmit() method

<form [formGroup]="employeeForm" (ngSubmit)="onSubmit()" class="form-horizontal">

So this method onSubmit(), is called when the employee form is submitted

mapFormValuesToEmployeeModel() method copies the edited values into the employee object

At this point, you may be thinking can't I simply type cast employeeForm.value to IEmployee type. 

this.employee = <IEmployee>this.employeeForm.value;

No, we can't do this because, the shape of employeeForm.value does not match with the shape of IEmployee

In employeeForm.value, we do not have id property. Also, email and conifrmEmail properties are present in a nested FormGroup called emailGroup in the employeeForm, where as in the IEmployee interface we do not have such an email group property. We only have email property on th IEmployee interface. confirmEmail form control in the employeeForm is only there for validation. We do not need to save it on the server.

Another approach is to use Object.assign() method as shown below.

this.employee = Object.assign({}, this.employee, this.employeeForm.value);

But this approach also will not work for us, because the employeeForm.value has an additional emailGroup property but not on the IEmploye interface. 

Hence, we need mapFormValuesToEmployeeModel() method to manually copy the edited values into the employee object so it could be saved to the 

The updateEmployee() method of Angular EmployeeService issues a PUT request to the server side REST API. Here is the updateEmployee() method for your reference

updateEmployee(employee: IEmployee): Observable<void> {
    return this.httpClient.put<void>(`${this.baseUrl}/${employee.id}`, employee, {
        headers: new HttpHeaders({
            'Content-Type': 'application/json'
        })
    })
        .pipe(catchError(this.handleError));
}

When the call to the REST API completes successfully, navigate the user to the list route

Angular Router service is required to navigate the user to the list route. So, please make sure to import and inject Angular Router service into the component class.

import { Router } from '@angular/router';


constructor(private fb: FormBuilder,
  private route: ActivatedRoute,
  private employeeService: EmployeeService,
  private router: Router) { }

At this point when you click the save button, the edited data should be saved and redirected to list route. You can see the saved changes in db.json file.

angular 6 tutorial for beginners

1 comment:

  1. Hi Sir,
    Please advise and revise code for updating skills:
    I am using different form control names from ones in the API (ISkills[]). Instead of below line:
    this.employee.skills = this.employeeForm.value.skills;

    I wrote below code lines( the result is working ok):
    const skillsFormArray = this.grayEmployeeForm.get('grayskills');
    const iskills: ISkill[] = [];
    for (let i = 0; i < skillsFormArray.length; i++) {
    iskills.push({
    skillName: this.grayEmployeeForm.value.grayskills[i].grayskillName,
    experienceInYears: this.grayEmployeeForm.value.grayskills[i].grayyears,
    proficiency: this.grayEmployeeForm.value.grayskills[i].grayproficiency
    });
    }
    this.employee.skills = iskills;

    ReplyDelete

It would be great if you can help share these free resources