Saturday 2 February 2019

Angular reactive forms put example

Angular reactive forms put example


In this topic 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. 



No comments:

Post a Comment