Categories

Friday, June 21, 2024
#919814419350 therichposts@gmail.com
AngularAngular 17Angular Ecommerce TemplatesAngular TemplatesBootstrap 5Free Ecommerce Templates

Create Ecommerce Website in Angular 17 using Bootstrap 5 Part 2 | Add to cart + mini cart

Create Ecommerce Website in Angular 17 using Bootstrap 5 Part 2 | Add to cart + mini cart

Hello guys how are you? Welcome back to my blog. Today in this blog I am going to Create Ecommerce Website in Angular 17 using Bootstrap 5 Part 2 | Add to cart + mini cart.


Guys is the live demo video for Part 2:

Live demo

Guys To enable the functionality where clicking the “Add to Cart” button adds a product to the mini cart in your Angular eCommerce application, you will need to modify the component that displays products (like ProductListComponent) to interact with the CartService. Here’s how to implement this:

First, ensure that your ProductListComponent has access to the CartService so that it can use it to add items to the cart. Modify product-list.component.ts to include the cart functionality:

import { Component } from '@angular/core';
import { Product } from '../../product.model';
import { ProductService } from '../../services/product.service';
import { CommonModule } from '@angular/common'
import { RouterLink, RouterOutlet } from '@angular/router';
import { CartService } from '../../services/cart.service';

@Component({
  selector: 'app-product-list',
  standalone: true,
  imports: [CommonModule, RouterOutlet, RouterLink],
  templateUrl: './product-list.component.html',
  styleUrl: './product-list.component.css'
})
export class ProductListComponent {
  products: Product[] = [];

  constructor(private productService: ProductService, private cartService: CartService) { }

  ngOnInit(): void {
    this.products = this.productService.getProducts();
  }
  addToCart(product: Product): void {
    this.cartService.addToCart(product);
  }
}

Next, update product-list.component.html to include an “Add to Cart” button with a click event that triggers the addToCart method:

<div class="container mt-4">
  <div class="row row-cols-1 row-cols-md-3 g-4">
    <div class="col" *ngFor="let product of products">
      <div class="card h-100">
        <a [routerLink]="['/product', product.id]" class="link-unstyled">
          <img src="{{ product.imageUrl }}" class="card-img-top" alt="{{ product.name }}">
          <div class="card-body">
            <h5 class="card-title">{{ product.name }}</h5>
            <p class="card-text">{{ product.description }}</p>
            <p class="card-text"><small class="text-muted">{{ product.price | currency }}</small></p>
          </div>
        </a>
        <div class="card-footer bg-white">
          <button class="btn btn-primary" (click)="addToCart(product)">Add to Cart</button>
        </div>
      </div>
    </div>
  </div>
</div>

To add a mini cart to your Angular eCommerce application, you’ll need to set up a way to manage cart items, display a mini cart summary on each page, and allow users to view or modify their cart contents. Below are the steps to create a basic mini cart feature:

Create a service to handle cart operations like adding items, removing items, and fetching the current cart contents.

ng generate service services/cart

In your cart.service.ts, define the necessary methods:

import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { Product } from '../product.model';

interface CartItem {
  product: Product;
  quantity: number;
}

@Injectable({
  providedIn: 'root'
})
export class CartService {
  private cartItems: CartItem[] = [];
  private cartItemsSubject = new BehaviorSubject<CartItem[]>([]);

  constructor() { }

  addToCart(product: Product): void {
    const existingItem = this.cartItems.find(item => item.product.id === product.id);
    if (existingItem) {
      existingItem.quantity++;
    } else {
      this.cartItems.push({ product, quantity: 1 });
    }
    this.cartItemsSubject.next(this.cartItems);
  }

  removeFromCart(product: Product): void {
    const index = this.cartItems.findIndex(item => item.product.id === product.id);
    if (index !== -1) {
      this.cartItems.splice(index, 1);
      this.cartItemsSubject.next(this.cartItems);
    }
  }

  getCartItems(): Observable<CartItem[]> {
    return this.cartItemsSubject.asObservable();
  }

  clearCart(): void {
    this.cartItems = [];
    this.cartItemsSubject.next(this.cartItems);
  }
}

Generate a new component to represent the mini cart:

ng generate component components/mini-cart

In your mini-cart.component.ts, subscribe to the cart items from the CartService:

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { CartService } from '../../services/cart.service';
import { Product } from '../../product.model';
import { CommonModule } from '@angular/common'
import { CartItem } from '../../cart-item.model'; // Ensure you have this model, see below for its creation

@Component({
  selector: 'app-mini-cart',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './mini-cart.component.html',
  styleUrl: './mini-cart.component.css'
})
export class MiniCartComponent implements OnInit {
  cartItems: Observable<CartItem[]>;  // Update this to use CartItem

  constructor(private cartService: CartService) {
    this.cartItems = this.cartService.getCartItems();  // This returns an Observable of CartItem[]
  }
  removeItem(item: Product): void {
    this.cartService.removeFromCart(item);
  }
  clearCart(): void {
    this.cartService.clearCart();
  }
  ngOnInit(): void {
  }
}

In mini-cart.component.html, display the cart items:

<div class="mini-cart">
    <h4>Your Cart</h4>
    <div *ngIf="(cartItems | async)?.length; else emptyCart">
      <button class="btn btn-danger mb-3" (click)="clearCart()">Clear Cart</button>
      <ul>
        <li *ngFor="let item of (cartItems | async)">
          {{ item.product.name }} - {{ item.product.price | currency }} x {{ item.quantity }}
          <button class="btn btn-primary" (click)="removeItem(item.product)">Remove</button>
        </li>
      </ul>
    </div>
    <ng-template #emptyCart>
      <p>Your cart is empty.</p>
    </ng-template>
  </div>
  

If you haven’t already, define a CartItem model which includes both the product and its quantity:

// src/app/cart-item.model.ts
import { Product } from './product.model';

export interface CartItem {
  product: Product;
  quantity: number;
}

Add the mini cart component to your application’s main layout, typically in the app.component.html or wherever your main navigation is located:

<app-navbar></app-navbar>
<app-mini-cart></app-mini-cart>
<router-outlet></router-outlet>
<app-footer></app-footer>

Add CSS in mini-cart.component.scss to style the mini cart:

.mini-cart {
  position: fixed;
  right: 20px;
  top: 50px;
  width: 200px;
  background: white;
  padding: 10px;
  box-shadow: 0 0 10px rgba(0,0,0,0.1);
  z-index: 1000;
}

ul {
  list-style-type: none;
  padding: 0;

  li {
    margin-bottom: 10px;
    button {
      margin-left: 10px;
    }
  }
}

Run your Angular application:

ng serve

Navigate to http://localhost:4200/ and test adding and removing products from the mini cart. This will display a summary of cart items on each page, enhancing user interaction and experience.

This basic mini cart implementation will help you manage cart operations effectively in your Angular eCommerce application. You can further enhance this by adding features like quantity adjustments, subtotal calculations, or integrating it with a checkout process.

Note: Friends, In this post, I just tell the basic setup and things, you can change the code according to your requirements.

I will appreciate that if you will tell your views for this post. Nothing matters if your views will be good or bad because with your views, I will make my next posts more good and helpful.

Jassa

Thanks

therichpost
the authortherichpost
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 14, Angular 15, Angular 16, Angular 17, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.