Build Shopping Cart in Angular 6


Create new folder named learnangular5withrealapps and select to this folder in Visual Studio Code

Open Terminal windows in Visual Studio Code and type: npm install -g @angular/cli to install Angular 6

Create new folder images in src\assets folder. Copy photo files to this folder




Create new folder, named entities in src\app folder. In this folder, create new entities class as below:

Product Entity

Create new TypeScript file named product.entity.ts as below:

export class Product {

    id: string;
    name: string;
    price: number;
    photo: string;

}

Item Entity

Create new TypeScript file named item.entity.ts as below:

import { Product } from './product.entity';

export class Item {

    product: Product;
    quantity: number;

}

Create new folder, named services in src\app folder. In this folder, create new TypeScript file, named product.service.ts as below:

import { Injectable } from '@angular/core';

import { Product } from '../entities/product.entity';

@Injectable()
export class ProductService {

    private products: Product[];

    constructor() {
        this.products = [
            { id: 'p01', name: 'name 1', price: 100, photo: 'thumb1.gif' },
            { id: 'p02', name: 'name 2', price: 200, photo: 'thumb2.gif' },
            { id: 'p03', name: 'name 3', price: 300, photo: 'thumb3.gif' }
        ];
    }

    findAll(): Product[] {
        return this.products;
    }

    find(id: string): Product {
        return this.products[this.getSelectedIndex(id)];
    }

    private getSelectedIndex(id: string) {
        for (var i = 0; i < this.products.length; i++) {
            if (this.products[i].id == id) {
                return i;
            }
        }
        return -1;
    }

}

Create new folder, named components in src\app folder. In this folder, create children components as below:

Product Component

Create new folder named product in src\app\components folder. In this folder, create new TypeScript file named product.component.ts

import { Component, OnInit } from '@angular/core';

import { Product } from '../../entities/product.entity';
import { ProductService } from '../../services/product.service';

@Component({
	templateUrl: 'index.component.html'
})

export class ProductComponent implements OnInit {

	private products: Product[];

	constructor(
		private productService: ProductService
	) { }

	ngOnInit() {
		this.products = this.productService.findAll();
	}


}

Create new file, named index.component.html contains html for product page

<h3>Product List</h3>
<table border="1">
    <tr>
        <th>Id</th>
        <th>Name</th>
        <th>Price</th>
        <th>Photo</th>
        <th>Buy</th>
    </tr>
    <tr *ngFor="let product of products">
        <td>{{product.id}}</td>
        <td>{{product.name}}</td>
        <td>{{product.price}}</td>
        <td>
            <img src="assets/http://learningprogramming.net/wp-content/uploads/mean_stack/angular/{{product.photo}}" width="50">
        </td>
        <td>
            <a [routerLink]="['/cart', { id:product.id }]">Buy Now</a>
        </td>
    </tr>
</table>




Cart Component

Create new folder named cart in src\app\components folder. In this folder, create new TypeScript file named cart.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

import { Product } from '../../entities/product.entity';
import { Item } from '../../entities/item.entity';
import { ProductService } from '../../services/product.service';

@Component({
	templateUrl: 'index.component.html'
})

export class CartComponent implements OnInit {

	private items: Item[] = [];
	private total: number = 0;

	constructor(
		private activatedRoute: ActivatedRoute,
		private productService: ProductService
	) { }

	ngOnInit() {
		this.activatedRoute.params.subscribe(params => {
			var id = params['id'];
			if (id) {
				var item: Item = {
					product: this.productService.find(id),
					quantity: 1
				};
				if (localStorage.getItem('cart') == null) {
					let cart: any = [];
					cart.push(JSON.stringify(item));
					localStorage.setItem('cart', JSON.stringify(cart));
				} else {
					let cart: any = JSON.parse(localStorage.getItem('cart'));
					let index: number = -1;
					for (var i = 0; i < cart.length; i++) {
						let item: Item = JSON.parse(cart[i]);
						if (item.product.id == id) {
							index = i;
							break;
						}
					}
					if (index == -1) {
						cart.push(JSON.stringify(item));
						localStorage.setItem('cart', JSON.stringify(cart));
					} else {
						let item: Item = JSON.parse(cart[index]);
						item.quantity += 1;
						cart[index] = JSON.stringify(item);
						localStorage.setItem("cart", JSON.stringify(cart));
					}
				}
				this.loadCart();
			} else {
				this.loadCart();
			}
		});
	}

	loadCart(): void {
		this.total = 0;
		this.items = [];
		let cart = JSON.parse(localStorage.getItem('cart'));
		for (var i = 0; i < cart.length; i++) {
			let item = JSON.parse(cart[i]);
			this.items.push({
				product: item.product,
				quantity: item.quantity
			});
			this.total += item.product.price * item.quantity;
		}
	}

	remove(id: string): void {
		let cart: any = JSON.parse(localStorage.getItem('cart'));
		let index: number = -1;
		for (var i = 0; i < cart.length; i++) {
			let item: Item = JSON.parse(cart[i]);
			if (item.product.id == id) {
				cart.splice(i, 1);
				break;
			}
		}
		localStorage.setItem("cart", JSON.stringify(cart));
		this.loadCart();
	}


}

Create new file, named index.component.html contains html for cart page

<h3>Cart Info</h3>
<table border="1">
    <tr>
        <th>Option</th>
        <th>Id</th>
        <th>Name</th>
        <th>Photo</th>
        <th>Price</th>
        <th>Quantity</th>
        <th>Sub Total</th>
    </tr>
    <tr *ngFor="let item of items">
        <td align="center">
            <a (click)="remove(item.product.id)">X</a>
        </td>
        <td>{{item.product.id}}</td>
        <td>{{item.product.name}}</td>
        <td>
            <img src="assets/http://learningprogramming.net/wp-content/uploads/mean_stack/angular/{{item.product.photo}}" width="50">
        </td>
        <td>{{item.product.price}}</td>
        <td>{{item.quantity}}</td>
        <td>{{item.product.price * item.quantity}}</td>
    </tr>
    <tr>
        <td colspan="6" align="right">Total</td>
        <td>{{total}}</td>
    </tr>
</table>




Create new TypeScript file, named app.routing.ts in src\app folder. This file contains routes of urls in template

import { Routes, RouterModule } from '@angular/router';

import { CartComponent } from './components/cart/cart.component';
import { ProductComponent } from './components/product/product.component';

const routes: Routes = [
	{ path: '', component: ProductComponent },
	{ path: 'products', component: ProductComponent },
	{ path: 'cart', component: CartComponent },
	{ path: '**', redirectTo: '' }
];

export const routing = RouterModule.forRoot(routes);

Create new TypeScript file, named app.component.ts in src\app folder.

import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'app-root',
    templateUrl: 'app.component.html'
})

export class AppComponent implements OnInit {

    ngOnInit() {
    }

}

Create new file, named app.component.html in src\app folder. This file is html template for application

<a [routerLink]="['/products']">Products</a> |
<a [routerLink]="['/cart']">Cart</a>
<br><br>
<router-outlet></router-outlet>

In app.module.ts file in src\app folder. Add components, services and routing to module

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

import { AppComponent } from './app.component';
import { CartComponent } from './components/cart/cart.component';
import { ProductComponent } from './components/product/product.component';

import { ProductService } from './services/product.service';

import { routing } from './app.routing';

@NgModule({
  declarations: [
    AppComponent,
    CartComponent,
    ProductComponent
  ],
  imports: [
    BrowserModule,
    routing
  ],
  providers: [
    ProductService
  ],
  bootstrap: [AppComponent]
})

export class AppModule { }

In Terminal windows in Visual Studio Code and type: ng serve --open, program will open url http://localhost:4200/ on browser




Products List Page

Cart Page

I recommend you refer to the books below to learn more about the knowledge in this article: