How to create shopping cart ionic7


Create a new app ionic

1. Install Node.js and NPM: Before you start creating your Ionic app, you need to install Node.js and NPM (Node Package Manager) on your computer. You can download and install them from the official website: .

2. Install Ionic CLI: Once you have Node.js and NPM installed, you can install the Ionic CLI by running the following command in your terminal or command prompt:


npm install -g @ionic/cli

This command will install the latest version of the Ionic CLI globally on your system.
1. Create a new Ionic app: To create a new Ionic app, run the following command in your terminal or command prompt:


ionic start myApp

To create a new app with a specific template, you can use the --type option followed by the template name. For example, to create a new app with the blank template, run the following command:

ionic start myApp --type=blank

1. Run the app: Once you have created your app, you can run it in the browser by running the following command:

cd myApp ionic serve

This will start a local development server and open your app in the default web browser. You can make changes to your app and see the changes live in the browser.
That's it! You have now created a new Ionic app and are ready to start building your own mobile app.

We need to generate service

1. Open a command prompt or terminal and navigate to the root directory of your Ionic project.

2. Use the Ionic CLI to generate the service. Run the following command:


ionic generate service services/cart

3. Open the generated service file (.service.ts) in your preferred code editor.

4. In the service file, you can define your service class and its methods. For example:

Once you have defined your service methods, you can use this service in your components or other parts of your Ionic application by importing it and injecting it as a dependency.

We need creation an interface inside CartService using CSS or by leveraging Ionic's utility classes and predefined themes.

Cart service


export interface Product { id: number; name: string; price: number; amount: number; image: string; }

Create data

Declare an array variable and specify the data type of the array elements using an interface. For example, let's say we want to create an array of Product objects:

You can now use the Product array in your code. Here's an example of how to loop through the array and display the name and age of each person:


data: Product[] = [ { id: 0, name: 'Pizza Salami', image: 'https://ichkocheheute.de/wp-content/uploads/2017/08/P1120510.jpg', price: 8.99, amount: 1 }, { id: 1, name: 'Checken wings', image: 'https://jesspryles.com/wp-content/uploads/2020/01/smoked-chicken-wings-46-scaled.jpg', price: 5.49, amount: 1 }, { id: 2, name: 'Burger king', image: 'https://tofuu.getjusto.com/orioneat-prod-ss-upload/LtvaKSb9njo92HpgnHnC', price: 4.99, amount: 1 }, { id: 3, name: 'Salade', image: 'https://img.cuisineaz.com/660x660/2013/12/20/i34581-salade-nicoise-rapide.jpeg', price: 6.99, amount: 1 }, { id: 4, name: 'Rice casserole', image: 'https://www.hiddenvalley.com/wp-content/uploads/2021/04/cheesy-ranch-ground-beef-rice-casserole-RDP.jpg', price: 5.80, amount: 1 } ];

That's it! You have created an array using an interface in Ionic using TypeScript. Feel free to modify the interface and array structure to fit your specific needs.

BehaviorSubject

In Ionic, you can use the RxJS BehaviorSubject service to create an observable that emits the most recent value to new subscribers and keeps track of the current value.

Here's an example of how to use the BehaviorSubject service in an Ionic application:

1. Import the necessary modules and services:

Declare a variable of type BehaviorSubject in your component or service:

2. Update the value of the BehaviorSubject using the next method:


import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class CartService { private cart = []; private cartItemCount = new BehaviorSubject(0); constructor() { } Create a metod to get all products getProducts(): Product[] { return this.data; } Create a metod to get cart getCart() { return this.cart; } Create a metod to get cart item count getCartItemCount() { return this.cartItemCount; } Create a metod to add product addProduct(product) { let added = false; for (const p of this.cart) { if (p.id === product.id) { p.amount += 1; added = true; break; } } if(!added) { this.cart.push(product); } this.cartItemCount.next(this.cartItemCount.value + 1); } Create a metod to descreamse product decreaseProduct(product) { for (const [index, p] of this.cart.entries()) { if (p.id === product.id) { p.amount -= 1; if (p.amount === 0) { this.cart.slice(index, 1); } } } this.cartItemCount.next(this.cartItemCount.value - 1); } Create a metod to remove product removeProduct(product) { for (const [index, p] of this.cart.entries()) { if (p.id === product.id) { this.cartItemCount.next(this.cartItemCount.value - p.amount); this.cart.splice(index, 1); } } } }

Remember to unsubscribe from the BehaviorSubject when you no longer need it to prevent memory leaks. You can do this by storing the subscription in a variable and calling unsubscribe on it when necessary:

By following these steps, you can effectively use the BehaviorSubject service in your Ionic application to handle and share state between components or services.

ViewChild and ElementRef

In Ionic, the ViewChild and ElementRef combination is commonly used to access and manipulate DOM elements or components within your templates. Here's how you can use them together:

1. Import the required modules:
2. Define the ViewChild property in your component:
In the @ViewChild decorator, 'elementRefName' should be replaced with the template reference variable name of the element you want to access.

1. Use the elementRef property to access the DOM element or component in your component methods or lifecycle hooks:

1. Implement the service: Open the generated service file and define the functionality and properties of your service.

2. Provide the service: In the same service file, you need to add the @Injectable() decorator above the class declaration. This decorator marks the class as injectable and allows it to be provided to other components.

3. Register the service: In your app's module file (usually app.module.ts), import the service and add it to the providers array or NgModule's providers property. This registers the service with the Angular dependency injection system.

Here's an example of injecting a service into a constructor in Ionic:

home.page.ts

import {Component, ElementRef, OnInit, ViewChild} from '@angular/core'; import {CartService} from '../services/cart.service'; import {ModalController} from '@ionic/angular'; import {BehaviorSubject} from 'rxjs'; import {CartModalPage} from '../pages/cart-modal/cart-modal.page'; @Component({ selector: 'app-home', templateUrl: 'home.page.html', styleUrls: ['home.page.scss'], }) export class HomePage implements OnInit { cart = []; products = []; cartItemCount: BehaviorSubject<number>; @ViewChild('cart', {static: false, read: ElementRef})fab: ElementRef; constructor(private cartService: CartService, private modalCtrl: ModalController) {} ngOnInit(): void { this.products = this.cartService.getProducts(); this.cart = this.cartService.getCart(); this.cartItemCount = this.cartService.getCartItemCount(); } addCart(p) { this.animateCSS('tada'); this.cartService.addProduct(p); } async openCart() { this.animateCSS('bounceOutLeft', true); const modal = await this.modalCtrl.create({ component: CartModalPage, cssClass: 'cart-modal' }); modal.onWillDismiss().then(() => { this.fab.nativeElement.classList.remove('animated', 'bounceOutLeft'); this.animateCSS('bounceInLeft'); }); modal.present(); } animateCSS(animationName, keepAnimated = false) { const node = this.fab.nativeElement; node.classList.add('animated', animationName); function handleAnimationEnd() { if (!keepAnimated) { node.classList.remove('animated', animationName); } node.removeEventListener('animationend', handleAnimationEnd); } node.addEventListener('animationend', handleAnimationEnd); } }

In the example above, the MyService is injected into the constructor of the MyComponent class by specifying it as a parameter. The private access modifier in front of the parameter automatically creates a class-level property with the same name, and the dependency injection system provides an instance of the MyService class when creating an instance of MyComponent.

Display data in html ionic

1. To display data in HTML using Ionic, you can use Angular's data binding features. Here's an example of how you can accomplish that: 2. Start by creating a new Ionic project or navigate to your existing project directory. 3. Open the desired HTML file where you want to display the data. For example, let's say you have a file called home.page.html. 4. Inside the HTML file, use Angular's interpolation syntax ({{ }}) to display the data dynamically. For instance, let's assume you have an array of items called items that you want to display:

home.page.html

<ion-header [translucent]="true"> <ion-toolbar color="danger"> <ion-title> Ionic sopping cart </ion-title> </ion-toolbar> </ion-header> <ion-content> <ion-fab vertical="top" horizontal="end" slot="fixed"> <ion-fab-button (click)="openCart()" #cart> <div class="cart-length">{{cartItemCount | async}}</div> <ion-icon name="cart" class="cart-icon"></ion-icon> </ion-fab-button> </ion-fab> <ion-list> <ion-card *ngFor="let p of products"> <img alt="Silhouette of mountains" src="{{p.image}}" /> <ion-card-header> <ion-card-title>{{p.name}}</ion-card-title> </ion-card-header> <ion-card-content> <ion-row class="ion-align-items-center"> <ion-col size="8"> <ion-label color="danger"> <b>{{p.price | currency:'USD'}}</b> </ion-label> </ion-col> <ion-col size="4" class="ion-text-right"> <ion-button fill="clear" (click)="addCart(p)"> <ion-icon name="add"></ion-icon> </ion-button> </ion-col> </ion-row> </ion-card-content> </ion-card> </ion-list> </ion-content>

In this example, we're using *ngFor to iterate over the items array and display each item within an ion-item component. The {{ item }} syntax displays the value of each item. 1. In your corresponding TypeScript file (e.g., home.page.ts), define the items array and assign it some data. For example:

2. Here, we've declared the items array as a property of the HomePage class and assigned it some sample data.

That's it! When you run your Ionic app, the items array will be displayed in the HTML file using Angular's data binding.

Custom css

Open the home.page.scss file and start writing your custom CSS code. You can define styles for specific elements or create your own classes.

home.page.scss

ion-fab-button { height: 70px; width: 70px; } .cart-icon { font-size: 50px; } .cart-length { color: var(--ion-color-primary); position: absolute; top: 20px; left: 25px; font-weight: 600; font-size: 1em; min-width: 25px; z-index: 10; } img { height: 240px; width: 100%; }

Cart page ts

add item to cart shopping

1. Once you've found the item, click on it to view its details and options.

2. Choose the specific item, amount, or any other options if applicable.

3. Look for an "Add to Cart" or "Buy Now" button and click on it. This action should add the item to your shopping cart.

4. If prompted, you may need to select the quantity of the item you want to purchase.

Continue shopping if you want to add more items to your cart, or proceed to the checkout page to complete your purchase.

cart.page.ts

import { Component, OnInit } from '@angular/core'; import {CartService, Product} from '../../services/cart.service'; import {ModalController} from '@ionic/angular'; @Component({ selector: 'app-cart-modal', templateUrl: './cart-modal.page.html', styleUrls: ['./cart-modal.page.scss'], }) export class CartModalPage implements OnInit { cart: Product[] = []; constructor( private cartService: CartService, private modalCarl: ModalController) { } ngOnInit() { this.cart = this.cartService.getCart(); } decreaseCartItem(p) { this.cartService.decreaseProduct(p); } increaseCartItem(p) { this.cartService.addProduct(p); } removeCartItem(p) { this.cartService.removeProduct(p); } getTotal() { return this.cart.reduce((i, j) => i + j.price * j.amount, 0); } close() { this.modalCarl.dismiss(); } }

In the above example, CartModalPage has a button that triggers the callMyMethod() function, which calls myMethod() from MyComponent by accessing the instance of MyComponent through dependency injection.

Cart Page Html

Inside the HTML file, use Angular's interpolation syntax ({{ }}) to display the data dynamically. For instance, let's assume you have an array of items called items that you want to display:


<ion-content fullscreen> <div class="ion-text-end"> <ion-button (click)="close()" fill="clear" color="danger"> <ion-icon name="close" slot="start"></ion-icon> </ion-button> </div> <div class="ion-padding"> <ion-list> <ion-item *ngFor="let p of cart" class="ion-text-wrap"> <ion-grid> <ion-row> <ion-col size="4"> <ion-thumbnail> <img src="{{p.image}}" /> </ion-thumbnail> </ion-col> <ion-col size="4"> <b>{{p.name}}</b> </ion-col> <ion-col size="1"> {{p.amount}} </ion-col> <ion-col size="3" class="ion-text-end"> {{p.amount * p.price | currency:'USD'}} </ion-col> </ion-row> <ion-row> <ion-col size="4"> <ion-button color="medium" fill="clear" (click)="decreaseCartItem(p)"> <ion-icon name="remove-circle" slot="icon-only"> </ion-icon> </ion-button> </ion-col> <ion-col size="4"> <ion-button color="success" fill="clear" (click)="increaseCartItem(p)"> <ion-icon name="add-circle" slot="icon-only"></ion-icon> </ion-button> </ion-col> <ion-col size="4"> <ion-button color="danger" fill="clear" (click)="removeCartItem(p)"> <ion-icon name="close-circle" slot="icon-only"></ion-icon> </ion-button> </ion-col> </ion-row> </ion-grid> </ion-item> <ion-item> <ion-grid> <ion-row> <ion-col size="9"> Total: </ion-col> <ion-col size="3" class="ion-text-end"> {{getTotal() | currency:'USD'}} </ion-col> </ion-row> </ion-grid> </ion-item> </ion-list> <ion-button expand="block" size="small" color="success">Check in</ion-button> </div> </ion-content>

Remember to import the necessary components, services, or modules and adjust the paths accordingly based on your project structure.

Please note that this is a basic example, and you can customize it to suit your specific needs. You may need to adjust the code based on your project structure or the way you fetch and handle data.

Post a Comment

Previous Post Next Post