Complete CRUD Operation With Angular 9 Step by Step – PART 3

CRUD Operations with Angular - Part 3

This is Part 3 of Complete CRUD Operations in Angular(GET, POST, PUT and DELET). Here’s Part 1 and Part 2.

In this part we would see how to display a modal popup and submit a new record to the server. We’ll cover the following:

  1. Check the REST Endpoint
  2. Setup the Modules
  3. Code to Display Modal Popup
  4. Create Form Controls
  5. Handle Form Submission
  6. Next Steps

 

1. Check the REST EndPoint

Since we build the API ourself, remember? We would have to check the the endpoint for processing POST request works fine. This is in the Spring Boot API application. See how the post method looks like below:

@PostMapping("/friends/addnew")
public void addFriend(@RequestBody Friend friend){
    friendService.save(friend);
}

 

2. Set up the Modules

Take the following steps:

Step 1: First, we need to add click event to the Add-New button. Here’s the code, just add it to the button.

(click)="open(content)"

Step 2: In the app.module.ts, add  FormsModule and NgbModule to the imports section

Step 3: In your friends ts file, import ModalDismissReasons and NgbModal like so:

import {ModalDismissReasons, NgbModal} from '@ng-bootstrap/ng-bootstrap';

Step 4: Add NgbModal variable as parameter to the constructor. That is in addition to HTTPClient. Here’s the code

private modalService: NgbModal

Step 5: Add an attribute closeResult as a string attribute to the FriendComponent class.

 

3. Code to Display Modal Popup

Step 1: Then we add the html template for the modal.  All these are very easy. We’ll just go to NgBootstrap site and copy the codes.

Here’s the template. I removed the DateOfBirth field just to make it look simpler.

<ng-template #content let-modal>
  <div class="modal-header">
    <h4 class="modal-title" id="modal-basic-title">New Friend</h4>
    <button type="button" class="close" aria-label="Close" (click)="modal.dismiss('Cross click')">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="modal-body">
    <form>
      <div class="form-group">
        <label for="firstname">Firstname</label>
        <div class="input-group">
          <input id="firstname" class="form-control" >
        </div>
      </div>
    </form>
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-outline-dark" (click)="modal.close('Save click')">Save</button>
  </div>
</ng-template>

Step 2: Then you also need the TypeScript code as well. Here’s the type script code

open(content) {
  this.modalService.open(content, {ariaLabelledBy: 'modal-basic-title'}).result.then((result) => {
    this.closeResult = `Closed with: ${result}`;
  }, (reason) => {
    this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
  });
}

private getDismissReason(reason: any): string {
  if (reason === ModalDismissReasons.ESC) {
    return 'by pressing ESC';
  } else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
    return 'by clicking on a backdrop';
  } else {
    return `with: ${reason}`;
  }
}

 

4. Create all the Form Controls

You now need to create all the other form controls by copying and pasting the markup for Firstname. Then rename to have Lastname, Department, Email and Country. You don’t need to include the input for Id because it is auto-generated column. If you get it right, this is what it would look like when you click the “New Friend” button

Note: you have to set the name and the id. I recommend setting them to the same value. Then very important, add ngModel to the markup as well. NgModel helps bind the content of the form to the data field.

<div class="form-group">
  <label for="firstname">Firstname</label>
  <div class="input-group">
    <input id="firstname" name="firstname" class="form-control" ngModel>
  </div>
</div>
<div class="form-group">
  <label for="lastname">Lastname</label>
  <div class="input-group">
    <input id="lastname" name="lastname" class="form-control" ngModel>
  </div>
</div>
New Friend Input Form

Angular New Friend Input Form

 

5. Handling Form Submission

Similar to the way function for GET request, we can also write a function for post request. This function will be executed when a submit button inside the form is clicked. So let’s just change the existing Save button to Cancel. Then we add a new Submit button inside the form

Step 1: Change the text of the Save button to Cancel

Step 2: Add a new button inside the form with this markup

<div class="border text-center">
<button data-dismiss="modal" class="btn btn-info">Submit</button>
</div>

Add this code just before the </form> tag. I have also enclosed in a div so I can be centered on the form.

Step 3: Add the submit markup in the form tag. So the form tag would have to change to this:

<form #f="ngForm" (ngSubmit)="onSubmit(f)" novalidate>

Step 4: Finally we need to add the function to execute on form submission. The onSubmit() function is given below

onSubmit(f: NgForm) {
  const url = 'http://localhost:8888/friends/addnew';
  this.httpClient.post(url, f.value)
    .subscribe((result) => {
      this.ngOnInit(); //reload the table
    });
  this.modalService.dismissAll(); //dismiss the modal
}

This code is also very clear. For the post request, you specify the url along with the form values.

 

6. Next Steps

If you have come this far, congrats! We are not done yet. However, if you have challenges, feel free to let me know in the comment box below. Also subscribe to my channel for explanations.

In the next part, we would work on displaying details of a selected record. Then we also cover editing and deleting.