Shopping Cart
Features Demonstrated
Code
View Model (shopping-cart.ts)
export interface CartItem {
id: number;
productId: number;
name: string;
price: number;
quantity: number;
image: string;
maxQuantity: number;
}
export class ShoppingCart {
cartItems: CartItem[] = [];
// Add item to cart
addToCart(product: { id: number; name: string; price: number; image: string; maxQuantity: number }) {
const existingItem = this.cartItems.find(item => item.productId === product.id);
if (existingItem) {
// Increase quantity if item already in cart
if (existingItem.quantity < existingItem.maxQuantity) {
existingItem.quantity++;
} else {
alert(`Maximum quantity (${existingItem.maxQuantity}) reached for ${existingItem.name}`);
}
} else {
// Add new item
this.cartItems.push({
id: Date.now(), // Simple ID generation
productId: product.id,
name: product.name,
price: product.price,
quantity: 1,
image: product.image,
maxQuantity: product.maxQuantity
});
}
}
// Update item quantity
updateQuantity(item: CartItem, newQuantity: number) {
if (newQuantity <= 0) {
this.removeItem(item);
} else if (newQuantity <= item.maxQuantity) {
item.quantity = newQuantity;
} else {
item.quantity = item.maxQuantity;
alert(`Maximum quantity is ${item.maxQuantity}`);
}
}
// Increase quantity
increaseQuantity(item: CartItem) {
if (item.quantity < item.maxQuantity) {
item.quantity++;
} else {
alert(`Maximum quantity (${item.maxQuantity}) reached`);
}
}
// Decrease quantity
decreaseQuantity(item: CartItem) {
if (item.quantity > 1) {
item.quantity--;
} else {
this.removeItem(item);
}
}
// Remove item from cart
removeItem(item: CartItem) {
const index = this.cartItems.indexOf(item);
if (index > -1) {
this.cartItems.splice(index, 1);
}
}
// Clear entire cart
clearCart() {
if (confirm('Are you sure you want to clear your cart?')) {
this.cartItems = [];
}
}
// Proceed to checkout
checkout() {
console.log('Proceeding to checkout with:', this.cartItems);
alert('Proceeding to checkout...');
// In a real app, navigate to checkout page or open checkout modal
}
}Currency Value Converter (currency-value-converter.ts)
Template (shopping-cart.html)
Styles (shopping-cart.css)
How It Works
1. Lambda Expressions in Templates
2. Array Manipulation
3. Benefits of Lambda Expressions
4. Efficient List Updates
5. Quantity Validation
6. Conditional Rendering
7. Currency Formatting with Value Converter
8. When to Use Lambda Expressions vs Computed Properties
Variations
Persist Cart to LocalStorage
Add Discount Codes
Cart as a Service
Related
Last updated
Was this helpful?