Angular 7 – CRUD Operations

This is very huge post which covers most of the angular concepts , so please be patient and go through it. This post is related to angular CRUD operations using angular AG grid and REST webservices in java. We will go through below concepts while going through these post –

  1. REST API in java
  2. AG Grid in java
  3. Bootstrap Configuration
  4. Notifications service configuration
  5. Reactive forms in angular
  6. Form Validations
  7. Service in angular
  8. Calling REST API using HttpClient
  9. Routing and Navigation

1.REST API in java

We would need to create a REST API which supports CRUD operations on user data as below –

package com.myjavablog.controller;

import com.myjavablog.entity.User;
import com.myjavablog.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@CrossOrigin
@RestController
@RequestMapping("/api")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @GetMapping("/users")
    public List<User> getUsers(){
        return userRepository.findAll();
    }

    @GetMapping("/user/{id}")
    public Optional<User> getUser(@PathVariable Long id){
        return userRepository.findById(id);
    }

    @DeleteMapping("/user/{id}")
    public boolean deleteUser(@PathVariable Long id){
        userRepository.deleteById(id);
        return true;
    }

    @PostMapping("/user")
    public User createUser(@RequestBody User user){
        return userRepository.save(user);
    }

    @PutMapping("/user")
    public User updateUser(@RequestBody User user){
        return userRepository.save(user);
    }

}

This is the controller in java which supports GET,UPDATE,PUT,POST operations on USER data.

You can download the entire code from below Github link –

2. AG Grid in java

Before actually going into angular project, you can go through my older posts on how to create angular project. https://www.myjavablog.com/2019/04/13/angular-installation-and-setup/

Once the project is created you need to install ag-grid support to it. Below packages needs to be installed for the same –

npm i --save ag-grid

You need to import this dependency in app.module.ts by adding below line under imports –

AgGridModule.withComponents(null)

Also you need to add CSS support for grid in styles.css

@import 'ag-grid-community/dist/styles/ag-grid.css';
@import 'ag-grid-community/dist/styles/ag-theme-blue.css

Then create a component using below command –

ng n c user

This will create new user component and create CSS, TS , html files. Add code to html file for grid –

<h2 class="header">Angular 7 AG Grid CRUD Operations Example</h2>
<a href="/addUser"><button class="btn btn-sm btn-success button">Add User</button></a>  
<button class="btn btn-sm btn-primary" (click)="editUser()">Edit User</button>  
<button class="btn btn-sm btn-danger" (click)="deleteUser()">Delete User</button>
<br><br>
<ag-grid-angular style="width: 100%; height: 600px;"
    class="ag-theme-blue"
    (gridReady)="onGridReady($event)"
    [columnDefs]="columnDefs"
    [rowData]="users"
    rowSelection="single"    
    pagination="true"
    paginationPageSize =25
    (selectionChanged)="onSelectionChanged($event)"
    (cellEditingStopped)="onCellEditingStopped($event)"
    (dataChanged)="onrowValueChanged($event)"
    >
</ag-grid-angular>

All the options specified in grid configuration are self explanatory. You also need Typescript file in order to perform CRUD operations . You get this from my github link.

3. Bootstrap Configuration

First install bootstrap by using below npm command –

npm install bootstrap

Then Add bootstrap to angular.json under styles-

"styles": [
              "src/styles.css",
              "node_modules/bootstrap/dist/css/bootstrap.min.css"              
            ],

4. Notifications service configuration

This service is to show the notifications to users. Use below npm command to install –

npm install angular-notifier

Add it into imports in app.module.ts and add custom options as well-

NotifierModule.withConfig( customNotifierOptions )

/**
 * Custom angular notifier options
 */
const customNotifierOptions: NotifierOptions = {
	position: {
		horizontal: {
			position: 'middle',
			distance: 12
		},
		vertical: {
			position: 'top',
			distance: 12,
			gap: 10
		}
	},
	theme: 'material',
	behaviour: {
		autoHide: 5000,
		onClick: false,
		onMouseover: 'pauseAutoHide',
		showDismissButton: true,
		stacking: 4
	},
	animations: {
		enabled: true,
		show: {
			preset: 'slide',
			speed: 300,
			easing: 'ease'
		},
		hide: {
			preset: 'fade',
			speed: 300,
			easing: 'ease',
			offset: 50
		},
		shift: {
			speed: 300,
			easing: 'ease'
		},
		overlap: 150
	}
};

Also you would need to add CSS for notifier in app.component.html file as below –

<link rel="stylesheet" href="https://unpkg.com/[email protected]/styles.css">

5. Reactive forms in angular

Now you need to create user form to add users –

<div class="row">

  <div class="col-md-6 col-md-offset-2">
      <h1><span class="badge badge-light" id="header">Add User</span></h1>
    <form [formGroup]="userForm" (ngSubmit)="onSubmit()">
      
      <div class="form-group">
            <label for="firstName">First Name:</label>
            <input type="text" class="form-control" formControlName="fname" id="fname">
            <div *ngIf="submitted && userForm.controls.fname.errors" class="error">
              <div *ngIf="userForm.controls.fname.errors.required">First name is required</div>
            </div>
      </div>

      <div class="form-group">
          <label for="lastName">Last Name:</label>
          <input type="text" class="form-control" formControlName="lname" id="lname">
          <div *ngIf="submitted && userForm.controls.lname.errors" class="error">
            <div *ngIf="userForm.controls.lname.errors.required">Last name is required</div>
          </div>
      </div>

      <div class="form-group">
        <label for="email">Email address:</label>
        <input type="email" class="form-control" formControlName="email" id="email1">
        <div *ngIf="submitted && userForm.controls.email.errors" class="error">
          <div *ngIf="userForm.controls.email.errors.required">Email is required</div>
        </div>
      </div>

      <div class="form-group">
          <label for="age">Age:</label>
          <input type="text" class="form-control" formControlName="age" id="age1">
          <div *ngIf="submitted && userForm.controls.age.errors" class="error">
            <div *ngIf="userForm.controls.age.errors.required">Age is required</div>
          </div>
      </div>

      <div class="form-group">
          <label for="mobile">Mobile:</label>
          <input type="text" class="form-control" formControlName="mobile" id="mob">
          <div *ngIf="submitted && userForm.controls.mobile.errors" class="error">
            <div *ngIf="userForm.controls.mobile.errors.required">Mobile number is required</div>
          </div>
      </div>

      <button class="btn btn-primary">Submit</button>
      <div *ngIf="invalidLogin" class="error">
        <div>Invalid credentials.</div>
      </div>
    </form>
  </div>

  <a routerLink="/users"><button class="btn btn-sm btn-success button">Back</button></a>
</div>

6. Form Validations

With reactive forms ,you can associate FormGroup and FormBuilder and access the form fields . Using these objects , you can also validate the form fields using angular Validators.

7. Services in Angular

We have to write the service to call the REST APIs and perform CRUD operations as below –

Create service using –

ng g s user

import { Injectable } from '@angular/core';
import { User } from './../model/user';
import {HttpClient} from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class UserService {

  apiUrl:string = "http://localhost:8081/api/";

  constructor(private http : HttpClient) { 
  }

  getUsers() {
    return this.http.get<User[]>(this.apiUrl+'users');
   }

   deleteUser(userId: number){
    return this.http.delete(this.apiUrl+'user/'+userId);
   }

   addUser(user: User){
     console.log(user);
     return this.http.post(this.apiUrl+ 'user/', user );
   }

   editUser(user: User){
    console.log(user);
    return this.http.put(this.apiUrl+ 'user/', user );
  }
 
}

8. Calling REST API using HttpClient

In above service, we are injecting HttpClient in constructor to call the REST API.

9. Routing and Navigation

We would need to provide routing for our application. So specific URI will be served by specific Component. Route configuration is provided in app-routing.module.ts as below –

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './components/login/login.component';
import { UserComponent } from './components/user/user.component';
import { AddUserComponent } from './components/user/add-user/add-user.component';

const routes: Routes = [
  {path:'users',  component:UserComponent},
  {path:'', component:LoginComponent},
  {path:'addUser', component:AddUserComponent},
  {path:'login', component:LoginComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  

exports: [RouterModule]
})
export class AppRoutingModule { }

You can download the code for this application from below github link –

Now build the application and serve it to the client –

ng build
ng serve

Now the application is ready to access on http://localhost:4200/-

Login screen

Angular ag grid showing all users
Add New User

User Editing
Updated last name and email

User Deleted

Form Validations

1 thought on “Angular 7 – CRUD Operations”

Leave a Comment

Bitnami