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

Angular reactive forms post example

Suggested Videos
Part 27 - Angular reactive forms edit example | Text | Slides
Part 28 - Angular populate formarray | Text | Slides
Part 29 - Angular reactive forms put example | Text | Slides

In this video 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 ID parameter, 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 POST request 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>

angular 6 tutorial for beginners

1 comment:

  1. Thank you for very good tutorial. I tried to use addEmployee method to add to ASP.NET Web Api. I have form array of FirstNames and LastNames, on Submit method I pass onSubmit(employeeForm.Value) {...}, The web api method is Post([FromBody] RefererViewModel ref) {} when I submit I hit the controller but nothing is happen, can you help on submitting form array to asp.net web api please. Thanks

    ReplyDelete

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