Saturday 2 February 2019

Angular reactive forms post example

Angular reactive forms post example



In this topic we will discuss collecting data from a reactive form and issuing a POST request to the REST API so the data is created on the server. 


If we get to the CreateEmployeeComponent and in the route if we do not have IDparameter, then we know we are creating a new employee and not editing an existing employee. 

So modify the code block in ngOnInit() as shown below. Notice in the ELSE block, we are initialising a new empty Employee object. 

this.route.paramMap.subscribe(params => {
  const empId = +params.get('id');
  if (empId) {
    this.getEmployee(empId);
  } else {
    this.employee = {
      id: null,
      fullName: '',
      contactPreference: '',
      email: '',
      phone: null,
      skills: []
    };
  }
});

Next, modify code in onSubmit() method as shown below. 
  • Check if the id property on the employee object is truthy.
  • IF it is, then we know we are editing an existing employee, so call updateEmployee() of the EmployeeService which issues a PUT request to the REST API.
  • ELSE, we know we are creating a new employee. So in this case, call addEmployee() method of the EmployeeService which issues a POSTrequest to the REST API.
onSubmit(): void {
  this.mapFormValuesToEmployeeModel();

  if (this.employee.id) {
    this.employeeService.updateEmployee(this.employee).subscribe(
      () => this.router.navigate(['list']),
      (err: any) => console.log(err)
    );
  } else {
    this.employeeService.addEmployee(this.employee).subscribe(
      () => this.router.navigate(['list']),
      (err: any) => console.log(err)
    );
  }
}

Here is the addEmployee() method of the EmployeeService for your reference. 

addEmployee(employee: IEmployee): Observable<IEmployee> {
    return this.httpClient.post<IEmployee>(this.baseUrl, employee, {
        headers: new HttpHeaders({
            'Content-Type''application/json'
        })
    })
    .pipe(catchError(this.handleError));
}

At this point, you should be able to create a new employee as well as edit an existing employee.  

The only issue at the moment is, whether you are creating a new employee or editing an existing employee, the page title always shows "Create Employee"

When editing, we want the page title to be "Edit Employee" and when creating a new employee, we want the page title to be "Create Employee".

Here are the steps to achieve this

Step 1 : At the component class level, include pageTitle property


pageTitle: string;

Step 2 : Modify the code block in ngOnInit() to set the pageTitle property accordingly. 

this.route.paramMap.subscribe(params => {
  const empId = +params.get('id');
  if (empId) {
    this.pageTitle = 'Edit Employee';
    this.getEmployee(empId);
  } else {
    this.pageTitle = 'Create Employee';
    this.employee = {
      id: null,
      fullName: '',
      contactPreference: '',
      email: '',
      phone: null,
      skills: []
    };
  }
});

Step 3 : Finally in the template, bind to the pageTitle property 

<div class="panel-heading">
  <h3 class="panel-title">{{pageTitle}}</h3>
</div>

No comments:

Post a Comment