Showing posts with label AngularJS. Show all posts
Showing posts with label AngularJS. Show all posts

Comparing Angular and React: Understanding the Key Differences

Angular and React are two of the most popular JavaScript libraries for building web applications. Both libraries are widely used by developers and have a large and active community of users. However, there are some key major differences between the two libraries that you should be aware of if you are considering using one of them for your next project.

One of the main key differences between Angular and React is the way in which they are structured. Angular is a full-featured framework that provides a wide range of features and tools for building web applications. It includes a router, a template engine, a dependency injection system, and many other features that make it easy to build complex and scalable applications. React, on the other hand, is a smaller library that is focused solely on the view layer of an application. It provides a powerful set of tools for building reusable UI components, but it does not include many of the other features that are found in Angular.

Another key difference between Angular and React is the way in which they handle data binding. Angular uses two-way data binding, which means that changes made to the UI are automatically reflected in the underlying data model, and vice versa. React, on the other hand, uses a unidirectional data flow, which means that data flows in only one direction, from the parent component to the child component. This can make it easier to understand how data is flowing through an application and can help to prevent errors and bugs.

A third difference between Angular and React is the way in which they are used in the development process. Angular applications are typically built using a combination of HTML templates, JavaScript code, and CSS styles. React applications, on the other hand, are built using a syntax called JSX, which allows developers to write HTML-like code directly in their JavaScript code. This can make it easier for developers to build complex UI elements and can make it easier to understand the structure of an application.

In summary, Angular and React are both powerful tools for building web applications, but they have some key differences that you should be familiar with. Angular is a full-featured framework that is well-suited for building complex and scalable applications, while React is a smaller library that is focused solely on the view layer of an application. Both libraries have their own strengths and weaknesses, and the right choice for your project will depend on your specific needs and requirements.

Creating a project in Angular 14 and connecting with Spring Boot and MySQL

 In this article, we will create a simple Angular 14 project and connect it with our spring boot project and MySQL. The spring boot project is already created in our previous article. You can view the article on this link. I am using Visual Studio Code to create the angular project.



1. First install Angular using the command 
"npm install -g@angular/cli"

2. Create a project using the command
"ng new PRODUCTUIBB"

3. Next install bootstrap using the command
"npm install --save bootstrap"

4. Now create two components for the Nav bar and Footer.
  "ng g c component/footer"
"ng g c component/navbar"

5. Next create pages to show the homepage, add a product, update a product and show all the products using the following commands.
 "ng g c pages/home"
"ng g c pages/addproduct"
"ng g c pages/products"
"ng g c pages/updateproduct"

6. Your project folder will look like this:


7. Go to app.component.html and add the following code in it:

<app-navbar></app-navbar>

<div class="container marginbottom">
  <router-outlet></router-outlet>
</div>

<div>
<app-footer></app-footer>
</div>


8. Now go to styles.css file and add the following code:

html {
  position: relative;
  min-height: 100%;
}

.footer{
  background-color: black;
  color: white;
  width: 100%;
  position: absolute;
  bottom: 0;
}

.margintop{
margin-top: 15vh;
}

.marginbottom{
  margin-bottom: 15vh;
}

.marginhome{
margin-top: 10vh;
}

9. To create a nav bar, go to navbar.component.html and add the following code:

<nav class="navbar navbar-expand-md navbar-dark bg-primary fixed-top">
  <div class="container-fluid">
    <a class="navbar-brand" href="#">BB Products</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse"
        data-bs-target="#navbarNav" aria-controls="navbarNav"
        aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNav">
      <ul class="navbar-nav">
        <li class="nav-item">
          <a class="nav-link active" aria-current="page" href="#">Home</a>
        </li>
        <li class="nav-item">
          <a class="nav-link " routerLink="/allproducts">Products List</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" routerLink="/addproduct">Add Products</a>
        </li>
      </ul>
    </div>
  </div>
</nav>


10. To create a footer, go to footer.component.html and add the following code:

<footer class="footer">
  <p class="text-center">&copy; Black Bichhu 2022</p>
</footer>

11. For creating the home page, paste the following code in home.component.html:

<div class="container marginhome">
<div id="carouselExampleCaptions" class="carousel slide"
        data-bs-ride="carousel">
  <div class="carousel-indicators">
    <button type="button" data-bs-target="#carouselExampleCaptions"
        data-bs-slide-to="0" class="active" aria-current="true"
        aria-label="Slide 1"></button>
    <button type="button" data-bs-target="#carouselExampleCaptions"
        data-bs-slide-to="1" aria-label="Slide 2"></button>
    <button type="button" data-bs-target="#carouselExampleCaptions"
        data-bs-slide-to="2" aria-label="Slide 3"></button>
  </div>
  <div class="carousel-inner">
    <div class="carousel-item active">
      <img src="/assets/2.jpg" class="d-block w-100 img-fluid" alt="img">
      <div class="carousel-caption  d-md-block my-5">
        <h1>Welcome to BB Products</h1>
        <p></p>
      </div>
    </div>
    <div class="carousel-item">
      <img src="/assets/1.jpg" class="d-block w-100 img-fluid" alt="...">
      <div class="carousel-caption  d-md-block">
        <h5>Product 1</h5>
        <p>Product 2 Desc</p>
      </div>
    </div>
    <div class="carousel-item">
      <img src="/assets/3.jpg" class="d-block w-100 img-fluid" alt="...">
      <div class="carousel-caption  d-md-block">
        <h5>Product 2</h5>
        <p>Product 2 Desc</p>
      </div>
    </div>
  </div>
  <button class="carousel-control-prev" type="button"
        data-bs-target="#carouselExampleCaptions" data-bs-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="visually-hidden">Previous</span>
  </button>
  <button class="carousel-control-next" type="button"
        data-bs-target="#carouselExampleCaptions" data-bs-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="visually-hidden">Next</span>
  </button>
</div>
<div class="text-center mt-5">
  <h3>Let's Start the process</h3>
</div>
<div class="text-center mb-5">
  <button type="button" class="btn btn-primary mx-3"
        routerLink="/allproducts">View Products</button>
  <button type="button" class="btn btn-success mx-3"
        routerLink="/addproduct">Add Products</button>
</div>
</div>

12. Add the following code in product.component.html file:

<div class="container margintop ">
  <h2 class="text-center">Products List</h2>
  <div class="bgcards row">
  <div class="productcard col-md-3 col-sm-5 m-4" *ngFor="let c of products">
    <h3><strong>{{c.name}}</strong></h3>
    <p><small> <strong>Product ID: </strong>{{c.id}}</small></p>
    <p><strong> Quantity: </strong>{{c.quantity}}</p>
    <p><strong>Price: </strong>{{c.price}}</p>
    <button type="button" (click)="onupdateProduct(c.id)"
        class="btn btn-warning mx-2">Edit</button>
    <button type="button" (click)="ondelProduct(c.id)"
        class="btn btn-danger mx-2" >Delete</button>

  </div>
</div>
</div>

also, add the following code in product.component.css file:

.productcard{

border-radius: 5px;
box-shadow: rgba(0, 0, 0, 0.25) 0px 14px 28px,
            rgba(0, 0, 0, 0.22) 0px 10px 10px;
text-align: center;
padding: 2%;
}

.productcard:hover{
  transform: scale(1.2);
}

.bgcards{
  justify-content: center;
}

13. To add products, add the following code in the addproduct.compont.html file:

<div class="container margintop">
  <h2 class="text-center">Add Product</h2>
<div class="addforms">
  <form #addForm="ngForm" (ngSubmit)="onAddProduct(addForm)">
    <div class="mb-3 ">

      <label for="name" class="form-label ">Product Name</label>
      <input type="text" class="form-control" ngModel name="name">

    </div>
    <div class="mb-3">
      <label for="quantity" class="form-label">Product Quantity</label>
      <input type="number" class="form-control" ngModel name="quantity">
    </div>
    <div class="mb-3">
      <label for="price" class="form-label">Product Price</label>
      <input type="number" class="form-control" ngModel name="price">
    </div>
    <div class="text-center mb-5">
      <button type="submit" class="btn btn-primary mx-3" >Submit</button>
      <button type="reset" class="btn btn-primary mx-3"
            id="clearform">Clear</button>
    </div>
  </form>
</div>
</div>

14. Now add the following code in updateproduct.compont.html file:

<div class="container margintop">
  <h2 class="text-center">Edit Product Details</h2>
<div class="addforms">
  <form (ngSubmit)="onupdate()">
    <div class="mb-3">

      <label for="name" class="form-label">Product Name</label>
      <input type="text" [(ngModel)]="product.name" class="form-control"
        ngModel name="name">

    </div>
    <div class="mb-3">
      <label for="quantity" class="form-label">Product Quantity</label>
      <input type="text" [(ngModel)]="product.quantity" class="form-control"
        ngModel name="quantity">
    </div>
    <div class="mb-3">
      <label for="price" class="form-label">Product Price</label>
      <input type="text" [(ngModel)]="product.price" class="form-control"
        ngModel name="price">
    </div>
    <div class="text-center mb-5">
      <button type="submit" class="btn btn-primary mx-3" >Update</button>
      <button type="reset" class="btn btn-primary mx-3"
            id="clearform">Clear</button>
      <button type="button" class="btn btn-primary mx-3"
            routerLink="/allproducts"
        id="clearform">Back</button>
    </div>
  </form>
</div>
</div>

15. Go to app-routing.module.ts and import the components and add the following code:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AddproductComponent } from
    './pages/addproduct/addproduct.component';
import { HomeComponent } from './pages/home/home.component';
import { ProductsComponent } from './pages/products/products.component';
import { UpdateproductComponent } from
    './pages/updateproduct/updateproduct.component';

const routes: Routes = [
  {path:"", component:HomeComponent},
  {path:"allproducts",component:ProductsComponent},
  {path:"addproduct", component:AddproductComponent},
  {path:"updateproduct/:id", component:UpdateproductComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }


16. Go to app.module.ts and import the following modules:

imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    FormsModule,ReactiveFormsModule,
  ],

17. Create a Product class using the code "ng g class products" and add the below code in it :

export class Product {
  id: number;
  name: string;
  quantity: number;
  price: number;
}

18. Next create a product service which will connect to our spring boot project:
 create service: "ng g service productservice"

now add the following code in product.service.ts file:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'
import { Observable } from 'rxjs';
import { Product } from './product';

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

  constructor(private http:HttpClient ) { }

  private baseUrl = 'http://localhost:8080/api/v1';


  public getProducts():Observable<Product[]>{
    return this.http.get<Product[]>(`${this.baseUrl}/all-products`);
  }

  public addProducts(product: Product):Observable<Product>{
    return this.http.post<Product>
        ('http://localhost:8080/api/v1/add-products',product);
  }

  public updateProducts( id: number,product: Product):Observable<Object>{
    return this.http.put(`${this.baseUrl}/update/${id}`,product);
  }

  public deleteProducts(productId: number):Observable<any>{
    return this.http.delete(`${this.baseUrl}/delete/${productId}`,
        { responseType: 'text' });
  }

  public getProductById(id: number):Observable<Product>{
    return this.http.get<Product>(`${this.baseUrl}/all-products-byid/${id}`);
  }
}


19. Go to addproduct.compont.ts file and add this:

import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Router, RouterLink } from '@angular/router';
import { Product } from 'src/app/product';
import { ProductService } from 'src/app/product.service';

@Component({
  selector: 'app-addproduct',
  templateUrl: './addproduct.component.html',
  styleUrls: ['./addproduct.component.css']
})
export class AddproductComponent implements OnInit {

  products: Product[];

  constructor(private productService:ProductService,) { }

  ngOnInit(): void {

  }

  public onAddProduct(addForm:NgForm){

    this.productService.addProducts(addForm.value).subscribe(
      (response:Product)=>{
        alert("Product Added Sucessfully");
      },
      (error:HttpErrorResponse)=>{
        alert(error.message)
      }
    )
    document.getElementById("clearform")?.click();
  }
}


20. Go to the file product.component.ts and add the following code:

import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Product } from 'src/app/product';
import { ProductService } from 'src/app/product.service';

@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.css']
})
export class ProductsComponent implements OnInit {

  products: Product[];


  constructor(private productService:ProductService,
        private route: Router) { }

  ngOnInit(): void {
    this.getProducts();

  }
  //getting all the products
  public getProducts(){
    this.productService.getProducts().subscribe(
      (response:Product[])=>{
        this.products=response;
      },
      (error: HttpErrorResponse)=>{
        alert(error.message);
      }
    )
  }

  //deleting product
  ondelProduct(employeeId:number){
    this.productService.deleteProducts(employeeId).subscribe(
      (response:void)=>{
        alert("Deleted");
        this.getProducts();
      },
      (error:HttpErrorResponse)=>{
        alert(error.message)
      }
    )
  }

  onupdateProduct(id: number){
    this.route.navigate(['updateproduct',id])
  }
}

21. Next go to updateproduct.component.ts file and paste the following code:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Product } from 'src/app/product';
import { ProductService } from 'src/app/product.service';

@Component({
  selector: 'app-updateproduct',
  templateUrl: './updateproduct.component.html',
  styleUrls: ['./updateproduct.component.css']
})
export class UpdateproductComponent implements OnInit {

  id: number;
  product: Product = new Product();
  constructor(private productService: ProductService,
    private activatedRoute:ActivatedRoute, private route:Router) { }

  ngOnInit(): void {
    this.id=this.activatedRoute.snapshot.params['id'];
    this.productService.getProductById(this.id).subscribe(
      (data)=>{this.product=data},
      (error)=>{alert(error.message)}
    )
  }

  onupdate(){
    this.productService.updateProducts(this.id, this.product).subscribe(
      (data)=>{alert("Updated Sucessfully"),this.gotoproductlist();},
      (error)=>{alert(error.message)},


  )
}

  gotoproductlist(){
    this.route.navigate(['/allproducts'])
  }

}


22. Now our project is ready. Start the angular project using the command "npm start", and also start the spring boot project. By default, the angular project will run on port no. 4200 and spring boot will run on port no. 8080.