Spring Angular CRUD Application

Last updated on May 31 2022
Santosh Prakash

Table of Contents

Spring Angular CRUD Application

In this blog, we are going to develop a CRUD (create-read-update-delete) web application. This application contains the student form that includes the CRUD features like add, view, delete, and update student. In this integration, we are using Spring Boot to handle the backend part and Angular to handle the frontend part.

Working of Application

  • Once we deployed our application on the server, a student form generates at the web browser.
  • The form facilitates to add and view students.
  • On clicking add student link, the page redirects to create student form where we can add a student by filling the required details and submit them.
  • Using view student link, we can fetch the details of the existing student. Here, each student also contains update and delete link.
  • So, we can update the details of the student and also delete them from the database.
  • Once completed, provide the URL http://localhost:4200/ at the web browser.

Tools to be used

  • Use any IDE to develop the Spring and Hibernate project. It may be STS/Eclipse/Netbeans. Here, we are using STS (Spring Tool Suite).
  • MySQL for the database.
  • Use any IDE to develop the Angular project. It may be Visual Studio Code/Sublime. Here, we are using Visual Studio Code.
  • Server: Apache Tomcat/JBoss/Glassfish/Weblogic/Websphere.

Technologies we used

Here, we are using the following technologies:

  • SpringBoot 2
  • Hibernate 5
  • Angular 6
  • MYSQL

Create Database

Let’s create a database indigo. There is no need to create a table as Hibernate automatically created it.

Spring Module

Let’s see the directory structure of Spring Boot we need to follow:

To develop a CRUD application, follow the below steps: –

  • Add dependencies to pom.xml file.
  1. <?xml version=”1.0″ encoding=”UTF-8″?>
  2. <project xmlns=”http://maven.apache.org/POM/4.0.0″ xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
  3.     xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”>
  4.     <modelVersion>4.0.0</modelVersion>
  5.     <parent>
  6.         <groupId>org.springframework.boot</groupId>
  7.         <artifactId>spring-boot-starter-parent</artifactId>
  8.         <version>2.1.4.RELEASE</version>
  9.         <relativePath/> <!– lookup parent from repository –>
  10.     </parent>
  11.     <groupId>com.main</groupId>
  12.     <artifactId>Student</artifactId>
  13.     <version>0.0.1-SNAPSHOT</version>
  14.     <name>Student</name>
  15.     <description>Demo project for Spring Boot</description>
  16.     <properties>
  17.         <java.version>1.8</java.version>
  18.     </properties>
  19.     <dependencies>
  20.         <dependency>
  21.             <groupId>org.springframework.boot</groupId>
  22.             <artifactId>spring-boot-devtools</artifactId>
  23.             <optional>true</optional>
  24.         </dependency>
  25.         <dependency>
  26.             <groupId>org.springframework.boot</groupId>
  27.             <artifactId>spring-boot-starter-data-jpa</artifactId>
  28.         </dependency>
  29.         <dependency>
  30.             <groupId>org.springframework.boot</groupId>
  31.             <artifactId>spring-boot-starter-web</artifactId>
  32.         </dependency>
  33.         <dependency>
  34.             <groupId>mysql</groupId>
  35.             <artifactId>mysql-connector-java</artifactId>
  36.             <scope>runtime</scope>
  37.         </dependency>
  38.         <dependency>
  39.             <groupId>org.springframework.boot</groupId>
  40.             <artifactId>spring-boot-starter-test</artifactId>
  41.             <scope>test</scope>
  42.         </dependency>
  43.     </dependencies>
  44.     <build>
  45.         <plugins>
  46.             <plugin>
  47.                 <groupId>org.springframework.boot</groupId>
  48.                 <artifactId>spring-boot-maven-plugin</artifactId>
  49.             </plugin>
  50.         </plugins>
  51.     </build>
  52. </project>
  • Create the configuration class
    Instead of XML, we perform annotation-based configuration. So, we create a class Config.java and specify the required configuration in it. However, there is one more configuration class StudentApplication.java. This class is provided by Spring Boot automatically.q

Config.java

  1. package config;
  2. import java.util.Properties;
  3. import javax.sql.DataSource;
  4. import org.springframework.beans.factory.annotation.Value;
  5. import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
  6. import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
  7. import org.springframework.context.annotation.Bean;
  8. import org.springframework.context.annotation.ComponentScan;
  9. import org.springframework.context.annotation.ComponentScans;
  10. import org.springframework.context.annotation.Configuration;
  11. import org.springframework.jdbc.datasource.DriverManagerDataSource;
  12. import org.springframework.orm.hibernate5.HibernateTransactionManager;
  13. import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
  14. import org.springframework.transaction.annotation.EnableTransactionManagement;
  15. import org.springframework.web.servlet.view.InternalResourceViewResolver;
  16. @Configuration
  17. @EnableTransactionManagement
  18. @EnableAutoConfiguration(exclude = { HibernateJpaAutoConfiguration.class})
  19. @ComponentScans(value = { @ComponentScan(“boot.entry”),
  20.           @ComponentScan(“Model”),
  21.           @ComponentScan(“Controller”),
  22.           @ComponentScan(“DAO”),
  23.           @ComponentScan(“Miscallaneous”),
  24.           @ComponentScan(“Service”)})
  25. public class Config {
  26.      @Value(“${db.driver}”)
  27.         private String DB_DRIVER;
  28.         @Value(“${db.password}”)
  29.         private String DB_PASSWORD;
  30.         @Value(“${db.url}”)
  31.         private String DB_URL;
  32.         @Value(“${db.username}”)
  33.         private String DB_USERNAME;
  34.         @Value(“${hibernate.dialect}”)
  35.         private String HIBERNATE_DIALECT;
  36.         @Value(“${hibernate.show_sql}”)
  37.         private String HIBERNATE_SHOW_SQL;
  38.         @Value(“${hibernate.hbm2ddl.auto}”)
  39.         private String HIBERNATE_HBM2DDL_AUTO;
  40.         @Value(“${entitymanager.packagesToScan}”)
  41.         private String ENTITYMANAGER_PACKAGES_TO_SCAN;
  42.         @Bean
  43.         public LocalSessionFactoryBean sessionFactory() {
  44.             LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
  45.             sessionFactory.setDataSource(dataSource());
  46.             sessionFactory.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);
  47.             Properties hibernateProperties = new Properties();
  48.             hibernateProperties.put(“hibernate.dialect”, HIBERNATE_DIALECT);
  49.             hibernateProperties.put(“hibernate.show_sql”, HIBERNATE_SHOW_SQL);
  50.             hibernateProperties.put(“hibernate.hbm2ddl.auto”, HIBERNATE_HBM2DDL_AUTO);
  51.             sessionFactory.setHibernateProperties(hibernateProperties);
  52.             return sessionFactory;
  53.         }
  54.         @Bean
  55.         public DataSource dataSource() {
  56.             DriverManagerDataSource dataSource = new DriverManagerDataSource();
  57.             dataSource.setDriverClassName(DB_DRIVER);
  58.             dataSource.setUrl(DB_URL);
  59.             dataSource.setUsername(DB_USERNAME);
  60.             dataSource.setPassword(DB_PASSWORD);
  61.             return dataSource;
  62.         }
  63.         @Bean
  64.         public HibernateTransactionManager transactionManager() {
  65.             HibernateTransactionManager txManager = new HibernateTransactionManager();
  66.             txManager.setSessionFactory(sessionFactory().getObject());
  67.             return txManager;
  68.         }
  69.         @Bean
  70.         public InternalResourceViewResolver jspViewResolver() {
  71.             InternalResourceViewResolver resolver= new InternalResourceViewResolver();
  72.             resolver.setPrefix(“/views/”);
  73.             resolver.setSuffix(“.jsp”);
  74.             return resolver;
  75.         }
  76.     }

StudentApplication.java

  1. package config;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication
  5. public class StudentApplication {
  6.     public static void main(String[] args) {
  7.         SpringApplication.run(StudentApplication.class, args);
  8.     }
  9. }
  • Create the entity class
    Here, we are creating an Entity/POJO (Plain Old Java Object) class.

Student.java

  1. package Model;
  2. import javax.persistence.Entity;
  3. import javax.persistence.GeneratedValue;
  4. import javax.persistence.GenerationType;
  5. import javax.persistence.Id;
  6. import javax.persistence.Table;
  7. @Entity
  8. @Table(name=”student”)
  9. public class Student {
  10.     @Id
  11.     @GeneratedValue(strategy=GenerationType.IDENTITY)
  12.     private int student_id;
  13.     private String student_name;
  14.     private String student_email;
  15.     private String student_branch;
  16.     public int getStudent_id() {
  17.         return student_id;
  18.     }
  19.     public void setStudent_id(int student_id) {
  20.         this.student_id = student_id;
  21.     }
  22.     public String getStudent_name() {
  23.         return student_name;
  24.     }
  25.     public void setStudent_name(String student_name) {
  26.         this.student_name = student_name;
  27.     }
  28.     public String getStudent_email() {
  29.         return student_email;
  30.     }
  31.     public void setStudent_email(String student_email) {
  32.         this.student_email = student_email;
  33.     }
  34.     public String getStudent_branch() {
  35.         return student_branch;
  36.     }
  37.     public void setStudent_branch(String student_branch) {
  38.         this.student_branch = student_branch;
  39.     }
  40. }
  • Create the DAO interface
    Here, we are creating the DAO interface to perform database related operations.

Student_DAO.java

  1. package DAO;
  2. import java.util.List;
  3. import Model.Student;
  4. public interface Student_DAO {
  5.     public boolean saveStudent(Student student);
  6.     public List<Student> getStudents();
  7.     public boolean deleteStudent(Student student);
  8.     public List<Student> getStudentByID(Student student);
  9.     public boolean updateStudent(Student student);
  10. }
  • Create the DAO interface implementation class

Student_DAO_Imp.java

  1. package DAO;
  2. import java.util.List;
  3. import org.hibernate.Session;
  4. import org.hibernate.SessionFactory;
  5. import org.hibernate.query.Query;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.stereotype.Repository;
  8. import Model.Student;
  9. @Repository
  10. public class Student_DAO_Imp  implements Student_DAO{
  11.     @Autowired
  12.     private SessionFactory sessionFactory;
  13.     @Override
  14.     public boolean saveStudent(Student student) {
  15.         boolean status=false;
  16.         try {
  17.             sessionFactory.getCurrentSession().save(student);
  18.             status=true;
  19.         } catch (Exception e) {
  20.             e.printStackTrace();
  21.         }
  22.         return status;
  23.     }
  24.     @Override
  25.     public List<Student> getStudents() {
  26.         Session currentSession = sessionFactory.getCurrentSession();
  27.         Query<Student> query=currentSession.createQuery(“from Student”, Student.class);
  28.         List<Student> list=query.getResultList();
  29.         return list;
  30.     }
  31.     @Override
  32.     public boolean deleteStudent(Student student) {
  33.         boolean status=false;
  34.         try {
  35.             sessionFactory.getCurrentSession().delete(student);
  36.             status=true;
  37.         } catch (Exception e) {
  38.             e.printStackTrace();
  39.         }
  40.         return status;
  41.     }
  42.     @Override
  43.     public List<Student> getStudentByID(Student student) {
  44.         Session currentSession = sessionFactory.getCurrentSession();
  45.         Query<Student> query=currentSession.createQuery(“from Student where student_id=:student_id”, Student.class);
  46.         query.setParameter(“student_id”, student.getStudent_id());
  47.         List<Student> list=query.getResultList();
  48.         return list;
  49.     }
  50.     @Override
  51.     public boolean updateStudent(Student student) {
  52.         boolean status=false;
  53.         try {
  54.             sessionFactory.getCurrentSession().update(student);
  55.             status=true;
  56.         } catch (Exception e) {
  57.             e.printStackTrace();
  58.         }
  59.         return status;
  60.     }
  61. }
  • Create the service layer interface

Here, we are creating a service layer interface that acts as a bridge between DAO and Entity classes.

Student_Service.java

  1. package Service;
  2. import java.util.List;
  3. import Model.Student;
  4. public interface Student_Service {
  5.     public boolean saveStudent(Student student);
  6.     public List<Student> getStudents();
  7.     public boolean deleteStudent(Student student);
  8.     public List<Student> getStudentByID(Student student);
  9.     public boolean updateStudent(Student student);
  10. }
  • Create the service layer implementation class

Student_Service_Imp.java

  1. package Service;
  2. import java.util.List;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.stereotype.Service;
  5. import org.springframework.transaction.annotation.Transactional;
  6. import DAO.Student_DAO;
  7. import Model.Student;
  8. @Service
  9. @Transactional
  10. public class Student_Service_Imp implements Student_Service {
  11.     @Autowired
  12.     private Student_DAO studentdao;
  13.     @Override
  14.     public boolean saveStudent(Student student) {
  15.         return studentdao.saveStudent(student);
  16.     }
  17.     @Override
  18.     public List<Student> getStudents() {
  19.         return studentdao.getStudents();
  20.     }
  21.     @Override
  22.     public boolean deleteStudent(Student student) {
  23.         return studentdao.deleteStudent(student);
  24.     }
  25.     @Override
  26.     public List<Student> getStudentByID(Student student) {
  27.         return studentdao.getStudentByID(student);
  28.     }
  29.     @Override
  30.     public boolean updateStudent(Student student) {
  31.         return studentdao.updateStudent(student);
  32.     }
  33. }
  • Create the controller class

Controller.java

  1. package Controller;
  2. import java.util.List;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.web.bind.annotation.CrossOrigin;
  5. import org.springframework.web.bind.annotation.DeleteMapping;
  6. import org.springframework.web.bind.annotation.GetMapping;
  7. import org.springframework.web.bind.annotation.PathVariable;
  8. import org.springframework.web.bind.annotation.PostMapping;
  9. import org.springframework.web.bind.annotation.RequestBody;
  10. import org.springframework.web.bind.annotation.RequestMapping;
  11. import org.springframework.web.bind.annotation.RestController;
  12. import Model.Student;
  13. import Service.Student_Service;
  14. @RestController
  15. @CrossOrigin(origins=”http://localhost:4200″)
  16. @RequestMapping(value=”/api”)
  17. public class Controller {
  18.     @Autowired
  19.     private Student_Service studentservice;
  20.     @PostMapping(“save-student”)
  21.     public boolean saveStudent(@RequestBody Student student) {
  22.          return studentservice.saveStudent(student);
  23.     }
  24.     @GetMapping(“students-list”)
  25.     public List<Student> allstudents() {
  26.          return studentservice.getStudents();
  27.     }
  28.     @DeleteMapping(“delete-student/{student_id}”)
  29.     public boolean deleteStudent(@PathVariable(“student_id”) int student_id,Student student) {
  30.         student.setStudent_id(student_id);
  31.         return studentservice.deleteStudent(student);
  32.     }
  33.     @GetMapping(“student/{student_id}”)
  34.     public List<Student> allstudentByID(@PathVariable(“student_id”) int student_id,Student student) {
  35.          student.setStudent_id(student_id);
  36.          return studentservice.getStudentByID(student);
  37.     }
  38.     @PostMapping(“update-student/{student_id}”)
  39.     public boolean updateStudent(@RequestBody Student student,@PathVariable(“student_id”) int student_id) {
  40.         student.setStudent_id(student_id);
  41.         return studentservice.updateStudent(student);
  42.     }
  43. }
  • Edit application.properties file
    Here, we are editing the application.properties file present inside the src/main/resources folder. The following file contains the configuration properties.

application.properties

  1. # Database
  2. db.driver= com.mysql.jdbc.Driver
  3. db.url= jdbc:mysql://localhost:3306/indigo
  4. db.username=root
  5. db.password=
  6. # Hibernate
  7. hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
  8. hibernate.show_sql=true
  9. hibernate.hbm2ddl.auto=update
  10. entitymanager.packagesToScan=Model

Angular Module

Let’s see the directory structure of Angular we need to follow:

image002 9
Module
  • Create an Angular project

Let’s create an Angular project by using the following command:

ng new Angular

image003 12
project
image004 8
project

Here, Angular is the name of the project.

Install Bootstrap CSS framework

Use the following command to install bootstrap in the project.

npm install bootstrap@3.3.7 –save

Now, include the following code in the style.css file.

  1. @import “~bootstrap/dist/css/bootstrap.css”;

Install Angular-DataTable

Use the following command to install angular datatable in the project.

npm install angular-datatable –save

image005 9
datatable

It is required to include DataTableModule in imports array of app.module.ts file.

  • Generate Components
    Open the project in visual studio and then use the following command to generate Angular components:
    ng g c AddStudent
    ng g c StudentList
image006 7
import

Let’s also create a service class by using the following command: –

ng g s Student

image007 6
command
  • Edit the app.module.ts file
    • Import Routing – Here, we are importing routing file (app-routing.module.ts) and include it in imports array.
    • Import ReactiveFormsModule – Here, we are importing ReactiveFormsModule for reactive forms and specify it in imports array.
    • Import HttpModule – Here, we are importing HttpModule for server requests and specifying it in imports array.
    • Register Service class – Here, we are mentioning the service class in provider’s array.
  1. import { BrowserModule } from ‘@angular/platform-browser’;
  2. import { NgModule } from ‘@angular/core’;
  3. import { AppRoutingModule } from ‘./app-routing.module’;
  4. import { AppComponent } from ‘./app.component’;
  5. import { FormsModule, ReactiveFormsModule } from ‘@angular/forms’;
  6. import { HttpClientModule } from ‘@angular/common/http’;
  7. import {DataTablesModule} from ‘angular-datatables’;
  8. import { StudentListComponent } from ‘./student-list/student-list.component’;
  9. import { AddStudentComponent } from ‘./add-student/add-student.component’;
  10. @NgModule({
  11.   declarations: [
  12.     AppComponent,
  13.     StudentListComponent,
  14.     AddStudentComponent,
  15.   ],
  16.   imports: [
  17.     BrowserModule,
  18.     AppRoutingModule,
  19.     FormsModule,
  20.     ReactiveFormsModule,
  21.     HttpClientModule,
  22.     DataTablesModule
  23.   ],
  24.   providers: [],
  25.   bootstrap: [AppComponent]
  26. })
  27. export class AppModule { }
  • Edit the app-routing.module.ts file
  1. import { NgModule } from ‘@angular/core’;
  2. import { Routes, RouterModule } from ‘@angular/router’;
  3. import { StudentListComponent } from ‘./student-list/student-list.component’;
  4. import { AddStudentComponent } from ‘./add-student/add-student.component’;
  5. const routes: Routes = [
  6.   { path: ”, redirectTo: ‘view-student’, pathMatch: ‘full’ },
  7.   { path: ‘view-student’, component: StudentListComponent },
  8.   { path: ‘add-student’, component: AddStudentComponent },
  9. ];
  10. @NgModule({
  11.   imports: [RouterModule.forRoot(routes)],
  12.   exports: [RouterModule]
  13. })
  14. export class AppRoutingModule { }
  • Edit the app.component.html file
  1. <div  class=”container-fluid”>
  2. <nav class=”navbar navbar-expand-sm bg-dark navbar-dark”>
  3.     <ul class=”navbar-nav”>
  4.       <li class=”nav-item “>
  5.         <a routerLink=”view-student” class=”nav-link” class=”btn btn-primary active” role=”button” >View Student</a>
  6.       </li>
  7.       <li class=”nav-item”>
  8.         <a  routerLink=”add-student” class=”nav-link” class=”btn btn-primary active” role=”button” >Add Student</a>
  9.       </li>
  10.     </ul>
  11.   </nav>
  12.     <router-outlet></router-outlet>
  13. </div>
  • Create the Student.ts class

Let’s create a class by using the following command: –

ng g class Student

image008 8
create

Now, specify the required fields within the Student class.

  1. export class Student {
  2.     student_id:number;
  3.     student_name:String;
  4.     student_email:String;
  5.     student_branch:String;
  6. }

The purpose of this class is to map the specified fields with the fields of Spring entity class.

  • Edit the student.service.ts file
  1. import { Injectable } from ‘@angular/core’;
  2. import { HttpClient } from ‘@angular/common/http’;
  3. import { Observable } from ‘rxjs’;
  4. @Injectable({
  5.   providedIn: ‘root’
  6. })
  7. export class StudentService {
  8.   private baseUrl = ‘http://localhost:8080/api/’;
  9.   constructor(private http:HttpClient) { }
  10.   getStudentList(): Observable<any> {
  11.     return this.http.get(`${this.baseUrl}`+’students-list’);
  12.   }
  13.   createStudent(student: object): Observable<object> {
  14.     return this.http.post(`${this.baseUrl}`+’save-student’, student);
  15.   }
  16.   deleteStudent(id: number): Observable<any> {
  17.     return this.http.delete(`${this.baseUrl}/delete-student/${id}`, { responseType: ‘text’ });
  18.   }
  19.   getStudent(id: number): Observable<Object> {
  20.     return this.http.get(`${this.baseUrl}/student/${id}`);
  21.   }
  22.   updateStudent(id: number, value: any): Observable<Object> {
  23.     return this.http.post(`${this.baseUrl}/update-student/${id}`, value);
  24.   }
  25. }
  • Edit the add-student.component.ts file
  1. import { Component, OnInit } from ‘@angular/core’;
  2. import { StudentService } from ‘../student.service’;
  3. import {FormControl,FormGroup,Validators} from ‘@angular/forms’;
  4. import { Student } from ‘../student’;
  5. @Component({
  6.   selector: ‘app-add-student’,
  7.   templateUrl: ‘./add-student.component.html’,
  8.   styleUrls: [‘./add-student.component.css’]
  9. })
  10. export class AddStudentComponent implements OnInit {
  11.   constructor(private studentservice:StudentService) { }
  12.   student : Student=new Student();
  13.   submitted = false;
  14.   ngOnInit() {
  15.     this.submitted=false;
  16.   }
  17.   studentsaveform=new FormGroup({
  18.     student_name:new FormControl(” , [Validators.required , Validators.minLength(5) ] ),
  19.     student_email:new FormControl(”,[Validators.required,Validators.email]),
  20.     student_branch:new FormControl()
  21.   });
  22.   saveStudent(saveStudent){
  23.     this.student=new Student();
  24.     this.student.student_name=this.StudentName.value;
  25.     this.student.student_email=this.StudentEmail.value;
  26.     this.student.student_branch=this.StudentBranch.value;
  27.     this.submitted = true;
  28.     this.save();
  29.   }
  30.   save() {
  31.     this.studentservice.createStudent(this.student)
  32.       .subscribe(data => console.log(data), error => console.log(error));
  33.     this.student = new Student();
  34.   }
  35.   get StudentName(){
  36.     return this.studentsaveform.get(‘student_name’);
  37.   }
  38.   get StudentEmail(){
  39.     return this.studentsaveform.get(‘student_email’);
  40.   }
  41.   get StudentBranch(){
  42.     return this.studentsaveform.get(‘student_branch’);
  43.   }
  44.   addStudentForm(){
  45.     this.submitted=false;
  46.     this.studentsaveform.reset();
  47.   }
  48. }
  • Edit the add-student.component.html file
  1. <h3>Create Student</h3>
  2. <div class=”row”>
  3.   <div class=”col-sm-4″></div>
  4.   <div class=”col-sm-4″ >
  5.     <div [hidden]=”submitted” style=”width: 400px;”>
  6.       <form [formGroup]=”studentsaveform” #savestudent (ngSubmit)=”saveStudent(saveStudent)”>
  7.           <div class=”form-group”>
  8.               <label for=”name”>Student Name</label>
  9.               <input type=”text” class=”form-control”  formControlName=”student_name” data-toggle=”tooltip”
  10.                  data-placement=”right” title=”Enter Student Name” >
  11.               <div class=”alert alert-danger” *ngIf = “(StudentName.touched) && (StudentName.invalid)”
  12.                 style=”margin-top: 5px;”>
  13.                   <span *ngIf=”StudentName.errors.required”>Student Name is Required</span>
  14.                     <span *ngIf = “StudentName.errors.minlength”>
  15.                         MinLength Error
  16.                     </span>
  17.                 </div>
  18.           </div>
  19.           <div class=”form-group”>
  20.               <label for=”name”>Student Email</label>
  21.               <input type=”text” class=”form-control” formControlName=”student_email”
  22.                 data-toggle=”tooltip” data-placement=”right” title=”Enter Student Email”>
  23.                 <div class=”alert alert-danger” *ngIf = “(StudentEmail.touched) && (StudentEmail.invalid)”
  24.                 style=”margin-top: 5px;”>
  25.                   <span *ngIf=”StudentEmail.errors.required”>Student Email is Required</span>
  26.                     <span *ngIf = “StudentEmail.errors.email”>
  27.                         Invalid Email Format
  28.                     </span>
  29.                 </div>
  30.           </div>
  31.           <div class=”form-group”>
  32.               <label for=”branch”>Student Branch</label>
  33.                 <select class=”form-control” formControlName=”student_branch” data-toggle=”tooltip”
  34.                       data-placement=”right” title=”Select Student Branch”>
  35.                     <option value=”null”>–Select Branch–</option>
  36.                   <option value=”B-Tech”>B-Tech</option>
  37.                   <option value=”BCA”>BCA</option>
  38.                   <option value=”MCA”>MCA</option>
  39.                   <option value=”M-Tech”>M-Tech</option>
  40.                 </select>
  41.           </div>
  42.           <button type=”submit” class=”btn btn-success”>Submit</button>
  43.       </form>
  44.   </div>
  45.   </div>
  46.   <div class=”col-sm-4″></div>
  47. </div>
  48. <div class=”row”>
  49.   <div class=”col-sm-4″></div>
  50.   <div class=”col-sm-4″>
  51.       <div [hidden]=”!submitted”>
  52.          <h4>Student Added SuccessFully!</h4>
  53.          <button (click)=”addStudentForm()” class=’btn btn-primary’>Add More Student</button>
  54.       </div>
  55.   </div>
  56.   <div class=”col-sm-4″></div>
  57. </div>

On clicking Add Student, the following page generates:

image009 3
Add Student

Now, fill the required details and submit them to add student.

  • Edit the student-list.component.ts file
  1. import { Component, OnInit } from ‘@angular/core’;
  2. import { StudentService } from ‘../student.service’;
  3. import { Student } from ‘../student’;
  4. import { Observable,Subject } from “rxjs”;
  5. import {FormControl,FormGroup,Validators} from ‘@angular/forms’;
  6. @Component({
  7.   selector: ‘app-student-list’,
  8.   templateUrl: ‘./student-list.component.html’,
  9.   styleUrls: [‘./student-list.component.css’]
  10. })
  11. export class StudentListComponent implements OnInit {
  12.  constructor(private studentservice:StudentService) { }
  13.   studentsArray: any[] = [];
  14.   dtOptions: DataTables.Settings = {};
  15.   dtTrigger: Subject<any>= new Subject();
  16.   students: Observable<Student[]>;
  17.   student : Student=new Student();
  18.   deleteMessage=false;
  19.   studentlist:any;
  20.   isupdated = false;
  21.   ngOnInit() {
  22.     this.isupdated=false;
  23.     this.dtOptions = {
  24.       pageLength: 6,
  25.       stateSave:true,
  26.       lengthMenu:[[6, 16, 20, -1], [6, 16, 20, “All”]],
  27.       processing: true
  28.     };
  29.     this.studentservice.getStudentList().subscribe(data =>{
  30.     this.students =data;
  31.     this.dtTrigger.next();
  32.     })
  33.   }
  34.   deleteStudent(id: number) {
  35.     this.studentservice.deleteStudent(id)
  36.       .subscribe(
  37.         data => {
  38.           console.log(data);
  39.           this.deleteMessage=true;
  40.           this.studentservice.getStudentList().subscribe(data =>{
  41.             this.students =data
  42.             })
  43.         },
  44.         error => console.log(error));
  45.   }
  46.   updateStudent(id: number){
  47.     this.studentservice.getStudent(id)
  48.       .subscribe(
  49.         data => {
  50.           this.studentlist=data
  51.         },
  52.         error => console.log(error));
  53.   }
  54.   studentupdateform=new FormGroup({
  55.     student_id:new FormControl(),
  56.     student_name:new FormControl(),
  57.     student_email:new FormControl(),
  58.     student_branch:new FormControl()
  59.   });
  60.   updateStu(updstu){
  61.     this.student=new Student();
  62.    this.student.student_id=this.StudentId.value;
  63.    this.student.student_name=this.StudentName.value;
  64.    this.student.student_email=this.StudentEmail.value;
  65.    this.student.student_branch=this.StudentBranch.value;
  66.    console.log(this.StudentBranch.value);
  67.    this.studentservice.updateStudent(this.student.student_id,this.student).subscribe(
  68.     data => {
  69.       this.isupdated=true;
  70.       this.studentservice.getStudentList().subscribe(data =>{
  71.         this.students =data
  72.         })
  73.     },
  74.     error => console.log(error));
  75.   }
  76.   get StudentName(){
  77.     return this.studentupdateform.get(‘student_name’);
  78.   }
  79.   get StudentEmail(){
  80.     return this.studentupdateform.get(‘student_email’);
  81.   }
  82.   get StudentBranch(){
  83.     return this.studentupdateform.get(‘student_branch’);
  84.   }
  85.   get StudentId(){
  86.     return this.studentupdateform.get(‘student_id’);
  87.   }
  88.   changeisUpdate(){
  89.     this.isupdated=false;
  90.   }
  91. }
  • Edit the student-list.component.html file
  1. <div class=”panel panel-default”>
  2.   <div class=”panel-heading”>
  3.       <h1 style=”text-align: center”>Students</h1><br>
  4.       <div class=”row” [hidden]=”!deleteMessage”>
  5.                 <div class=”col-sm-4″></div>
  6.                 <div class=”col-sm-4″>
  7.                         <div class=”alert alert-info alert-dismissible”>
  8.                                 <button type=”button” class=”close” data-dismiss=”alert”>×</button>
  9.                                 <strong>Student Data Deleted</strong>
  10.                         </div>
  11.                 </div>
  12.                 <div class=”col-sm-4″></div>
  13.         </div>
  14.     </div>
  15.   <div class=”panel-body”>
  16.       <table  class=”table table-hover table-sm” datatable [dtOptions]=”dtOptions”
  17.       [dtTrigger]=”dtTrigger”  >
  18.           <thead class=”thead-light”>
  19.               <tr>
  20.                   <th>Student Name</th>
  21.                   <th>Student Email</th>
  22.                   <th>Student Branch</th>
  23.                   <th>Action</th>
  24.               </tr>
  25.           </thead>
  26.           <tbody>
  27.                <tr *ngFor=”let student of students “>
  28.                   <td>{{student.student_name}}</td>
  29.                   <td>{{student.student_email}}</td>
  30.                   <td>{{student.student_branch}}</td>
  31.                   <td><button (click)=”deleteStudent(student.student_id)” class=’btn btn-primary’><i class=”fa fa-futboll-0″>Delete</i></button>
  32.                     <button (click)=”updateStudent(student.student_id)” class=’btn btn-info’
  33.                     data-toggle=”modal” data-target=”#myModal”>Update</button>
  34.                   </td>
  35.                 </tr>
  36.           </tbody><br>
  37.       </table>
  38.   </div>
  39. </div>
  40. <div class=”modal” id=”myModal”>
  41.         <div class=”modal-dialog”>
  42.           <div class=”modal-content”>
  43.                 <form [formGroup]=”studentupdateform” #updstu (ngSubmit)=”updateStu(updstu)”>
  44.             <!– Modal Header –>
  45.             <div class=”modal-header”>
  46.               <h4 class=”modal-title” style=”text-align: center”>Update Student</h4>
  47.             </div>
  48.             <!– Modal body –>
  49.             <div class=”modal-body” *ngFor=”let student of studentlist ” >
  50.                 <div [hidden]=”isupdated”>
  51.                     <input type=”hidden” class=”form-control”  formControlName=”student_id” [(ngModel)]=”student.student_id”>
  52.                             <div class=”form-group”>
  53.                                 <label for=”name”>Student Name</label>
  54.                                 <input type=”text” class=”form-control”  formControlName=”student_name” [(ngModel)]=”student.student_name”  >
  55.                             </div>
  56.                             <div class=”form-group”>
  57.                                 <label for=”name”>Student Email</label>
  58.                                 <input type=”text” class=”form-control” formControlName=”student_email” [(ngModel)]=”student.student_email”>
  59.                             </div>
  60.                             <div class=”form-group”>
  61.                                 <label for=”name”>Student Branch</label>
  62.                                   <select class=”form-control” formControlName=”student_branch” required>
  63.                                     <option value=”B-Tech” [selected]=”‘B-Tech’ == student.student_branch”>B-Tech</option>
  64.                                     <option value=”BCA” [selected]=”‘BCA’ == student.student_branch”>BCA</option>
  65.                                     <option value=”MCA” [selected]=”‘MCA’ == student.student_branch” >MCA</option>
  66.                                     <option value=”M-Tech” [selected]=”‘M-Tech’ == student.student_branch”>M-Tech</option>
  67.                                   </select>
  68.                             </div>
  69.                   </div>
  70.                   <div [hidden]=”!isupdated”>
  71.                       <h4>Student Detail Updated!</h4>
  72.                   </div>
  73.             </div>
  74.             <!– Modal footer –>
  75.             <div class=”modal-footer” >
  76.               <button type=”submit” class=”btn btn-success” [hidden]=”isupdated”>Update</button>
  77.               <button type=”button” class=”btn btn-danger” data-dismiss=”modal” (click)=”changeisUpdate()”>Close</button>
  78.             </div>
  79.         </form>
  80.           </div>
  81.         </div>
  82.       </div>

On clicking View Student, the following page generates:

image010 5
View Student

On clicking Update Student, the following bootstrap modal appears:

image012 2
Update Student

Here, we can update the details of the existing student.

On clicking Delete, the existing student is deleted from the database. Let’s see the result after deleting the particular student.

image015
Delete

So, this brings us to the end of blog. This Tecklearn ‘Spring Angular CRUD Application’ blog helps you with commonly asked questions if you are looking out for a job in Angular JS and Front-End Development. If you wish to learn Angular JS and build a career in Front-End Development domain, then check out our interactive, Angular JS Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

https://www.tecklearn.com/course/angular-js-training/

Angular JS Training

About the Course

Angular JS certification training is designed for developers who are responsible for building applications using AngularJS. Through a combination of presentations and hands-on practices, participants will explore Angular comprehensively and learn to build components, directives, template-driven forms, routing, etc. for complex data-centric (enterprise) applications. This Angular online training will update your knowledge and skills with the current Angular version to lift your career.

Why Should you take Angular JS Training?

  • The average salary for “Angular Developer” ranges from approximately $92,814 per year for a Developer to $113,069 per year for a Full Stack Developer (Indeed.com).
  • YouTube, Google, Cisco, Nike, Samsung, Microsoft, Forbes, BMW and many Fortune 500 companies are using Angular as their front-end development framework to deliver an engaging user experience.
  • Angular’s powerful cross-platform feature allows developers to build progressive web applications and native mobile applications.

What you will Learn in this Course?

Introduction to Angular

  • Introduction to Angular
  • Comparison between front-end tools
  • Angular Architecture
  • Building blocks of Angular
  • Angular Installation
  • Angular CLI
  • Angular CLI commands
  • Angular Modules

Angular Components and Data Binding

  • Working of Angular Applications
  • Angular App Bootstrapping
  • Angular Components
  • Creating A Component Through Angular CLI
  • Ways to specify selectors
  • Template and styles
  • Installing bootstrap to design application
  • Data Binding
  • Types of Data Binding
  • Component Interaction using @Input and @Output decorator
  • Angular Animations

TypeScript

  • What is TypeScript
  • Need of TypeScript
  • How to install TypeScript
  • Nodemon for monitoring changes
  • Interfaces in Class, String Templates, Maps,
  • Sets and Object Restructuring

Directives and Pipes in Angular

  • Angular Directives
  • @Component Directive
  • Structural Directives
  • Attribute Directives
  • Custom Directives
  • Pipes
  • Built-in Pipes
  • Chaining pipes
  • Custom pipes
  • Pipe Transform Interface & Transform Function
  • Pure and Impure pipes

Angular Services and Dependency Injection

  • Angular service
  • Need for a service
  • Dependency Injection
  • Creating a service
  • Hierarchical Injector
  • Injecting A Service into Another Service
  • Observables
  • RxJS Library
  • Angular’s Interaction with Backend
  • Parts of an Http Request
  • HttpClient

Forms in Angular

  • Forms in Angular
  • What are their functions
  • Advantages of Forms
  • Various Types of Forms
  • What is Angular Validation and Model driven approach

Angular Routing

  • Angular Routing
  • Angular Routing benefits and features
  • Building a single page application and updating it dynamically with Angular Routing
  • What is Parameter Routing
  • Router Lifecycle Hooks and Child Routes

Authentication and Security in Angular

  • What is Authentication?
  • Authentication and authorization
  • Types of Authentication
  • Where to store tokens?
  • JSON Web Tokens (JWT)
  • Authentication in Angular application
  • Security threats in web application

Testing Angular applications

  • Testing of Angular applications
  • Deployment of Angular Test Bed for testing on Angular framework
  • Setup of various tools for testing
  • Testing services in Angular Framework
  • E2E and Document Object Model testing

Got a question for us? Please mention it in the comments section and we will get back to you.

0 responses on "Spring Angular CRUD Application"

Leave a Message

Your email address will not be published. Required fields are marked *