Angular Spring Boot showing data in table

Here we will use Angular and Spring boot to show data in HTML table.

Spring boot

To start a spring project go to https://start.spring.io/

For this project we selected

  1. Java 1.8
  2. Spring Web
  3. Spring Data JPA
  4. MySQL Driver
Spring Initializer to start spring boot project
Fig: Spring Initializer to start spring boot project

Click on generate to download spring boot project then extract then project zip file and move to your project location.

Eclipse IDE is used to develop spring boot project.

How to import maven project in Eclipse

  1. Open Eclipse
  2. Click on File
  3. Click on import
  4. On select import wizard select Maven
  5. Click on existing maven Project
  6. Click on next
  7. Browse folder
  8. Click on finish

Now maven project is imported to eclipse.

Updation of project is required for that follw this steps

  1. Right click on project in project Explorer
  2. Select Maven Option
  3. Update Maven
Spring Boot Project Explorer
Spring Boot Project Explorer

ExampleApplication.java

 
package com.ebhor.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ExampleApplication {

	public static void main(String[] args) {
		SpringApplication.run(ExampleApplication.class, args);
	}

}

POM.xml

 


	4.0.0
	
		org.springframework.boot
		spring-boot-starter-parent
		2.7.2
		 
	
	com.ebhor
	mvc
	0.0.1-SNAPSHOT
	war
	mvc
	Spring MVC Example
	
		1.8
	
	
		
			org.springframework.boot
			spring-boot-starter-web
		
		
			org.springframework.boot
			spring-boot-starter-data-jpa
		
		
			org.springframework.boot
			spring-boot-starter-tomcat
			provided
		
		
			org.springframework.boot
			spring-boot-starter-test
			test
		
		
			mysql
			mysql-connector-java
			runtime
		
	
	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	

Application.properties

Here we configured spring datasource to connect with MySql Database.

 
spring.datasource.url=jdbc:mysql://localhost:3306/ebhor
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect


EmployeeController.java

EmployeeController is used to fetch employee list from EmployeeService and send it to client using RestController.

@CrossOrigin(origins = “http://localhost:4200”) annotation is used to allow access this url to angular project.

 
package com.ebhor.example.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ebhor.example.entity.Employee;
import com.ebhor.example.service.EmployeeService;

@RestController
@CrossOrigin(origins = "http://localhost:4200")
public class EmployeeController {
	@Autowired
	EmployeeService employeeService;
	@GetMapping("/")
	public Iterable getEmployess() {
		return employeeService.getEmployees();
	}
}

Employee.java

This is an Employee entity class which maps with database table employee.

 
package com.ebhor.example.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "employee")
public class Employee {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = "id")
	private int id;
	@Column(name = "name", nullable = false)
	private String name;
	@Column(name = "designation", nullable = false)
	private String designation;
	@Column(name = "mobileno", nullable = false)
	private String mobileNo;
	@Column(name = "mailid", nullable = false)
	private String mailId;
	@Column(name = "department", nullable = false)
	private String department;

	public Employee() {
	}

	public Employee(int id, String name, String designation, String mobileNo, String mailId, String department) {
		super();
		this.id = id;
		this.name = name;
		this.designation = designation;
		this.mobileNo = mobileNo;
		this.mailId = mailId;
		this.department = department;
	}

	@Override
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + ", designation=" + designation + ", mobileNo=" + mobileNo
				+ ", mailId=" + mailId + ", department=" + department + "]";
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDesignation() {
		return designation;
	}

	public void setDesignation(String designation) {
		this.designation = designation;
	}

	public String getMobileNo() {
		return mobileNo;
	}

	public void setMobileNo(String mobileNo) {
		this.mobileNo = mobileNo;
	}

	public String getMailId() {
		return mailId;
	}

	public void setMailId(String mailId) {
		this.mailId = mailId;
	}

	public String getDepartment() {
		return department;
	}

	public void setDepartment(String department) {
		this.department = department;
	}

}

EmployeeService.java

EmployeeServices fetch data from EmployeeDAO and pass to EmployeeController

 
package com.ebhor.example.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ebhor.example.dao.EmployeeDAO;
import com.ebhor.example.entity.Employee;
@Service
public class EmployeeService {
	@Autowired
	public EmployeeDAO employeeDAO;
	public Iterable getEmployees() {
		return employeeDAO.findAll();
	}
}

EmployeeDAO.java

Interface EmployeeDAO extends to CrudRepository which provice access to database table.

 
package com.ebhor.example.dao;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.ebhor.example.entity.Employee;
@Repository
public interface EmployeeDAO extends CrudRepository{
}

To test our spring boot project you can call url using browser or Postman API

Postman API
Fig: Postman API

Angular Project

Visual studio code IDE is used to develop this project.

npm -v is 8.5.5
ng –version
Package and Version
@angular-devkit/architect 0.1303.7 (cli-only)
@angular-devkit/core 13.3.7 (cli-only)
@angular-devkit/schematics 13.3.7 (cli-only)
@schematics/angular 13.3.7 (cli-only)

Angular Commands

  1. To create new project => ng new angularapp1
  2. Generate service => ng g s employee
  3. Start server => ng serve
Angular Project Explorer
Fig: Angular Project Explorer

index.html

Remove all existing body content.

add Bootstrap CDN in head section

 



  
  Angularapp1
  
  
  
  


  


app.module.ts

Here HttpClientModule is added in imports.

 
import { NgModule } from '@angular/core';
import {HttpClientModule} from '@angular/common/http';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Employee.ts

This file contains employee interface that is having all fields of employee.

 
export interface Employee{
    id: number,
    name: string,
    designation:string,
    mobileNo:string,
    mailId:string,
    department:string
}

employee.service.ts

This file contains a method getEmployees() to get the employee data from specified url.

 
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
import { Employee } from './employee';
@Injectable({
  providedIn: 'root'
})
export class EmployeeService {
  private url = "http://localhost:8080/"
  constructor(private http: HttpClient) { }
  getEmployees(): Observable {
    return this.http.get(this.url)
      .pipe(
        retry(2),
        catchError(this.handleError)
      );
  }
  private handleError(error: HttpErrorResponse) {
    if (error.status === 0) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong.
      console.error(
        Backend returned code ${error.status}, body was: , error.error);
    }
    // Return an observable with a user-facing error message.
    return throwError(() => new Error('Something bad happened; please try again later.'));
  }
}

app.component.ts

This fill access the EmployeeService class and get data of Employee to employess variable

 
import { Component, OnInit } from '@angular/core';
import { EmployeeService } from './employee.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  public employees: any;
  constructor(private _employeeService: EmployeeService) { }
  ngOnInit(): void {
    this.employees = this._employeeService.getEmployees()
      .subscribe(data => this.employees = data);
  }


}

app.component.html:

This is HTML file to show employee data

ngFor is used to loop employees and interpolation is used to show data or employee

 

Employee details are

Id Name Designation MobileNo MailId Department
{{employee.id}} {{employee.name}} {{employee.designation}} {{employee.mobileNo}} {{employee.mailId}} {{employee.department}}

Afterexecuting you will get following output.

Angular Spring boot Showing data in table
Fig: showing Employee data using spring boot and angular

Hope you understand how to use Angular and Spring boot to show data in HTML table..

Read More

Angularjs select : ng-repeat ng option default multiple select selected value