Home > Mobile >  How to get the total price? (ANGULAR)
How to get the total price? (ANGULAR)

Time:06-17

I've been trying to get the total price of cart items, but I can't? I tried to do a method that sums all prices and passes it to the template, but I couldn't.

Here is the Cart Component as you can see:

import { Component, Input, OnInit, EventEmitter, Output } from '@angular/core';
import { Product } from 'src/app/Model/Product';

@Component({
  selector: 'app-cart',
  templateUrl: './cart.component.html',
  styleUrls: ['./cart.component.css']
})
export class CartComponent implements OnInit {
  @Input() cartList: Product[] = []
  itemQuantities: number[] = [1,2,3,4,5,6,7,8,9,10]
  constructor() { }
  ngOnInit(): void {
  }

  DeleteItem(cartItem: Product){
    const indexOfCartItem = this.cartList.indexOf(cartItem)
    this.cartList.splice(indexOfCartItem, 1)
  }
}

Cart Template:

<section >
  <div >
    <ul *ngFor="let cartItem of cartList">
      <img src="{{ cartItem.img }}" />
      <li>{{ cartItem.name }}</li>
      <li>{{ cartItem.price }}</li>
      <button (click)="DeleteItem(cartItem)">Remove Item</button>
      <div>
        <select>
          <option *ngFor="let itemQuantity of itemQuantities">
            {{ itemQuantity }}
          </option>
        </select>
      </div>
    </ul>
    <div *ngFor="let carts of cartList"><p>Total price</p></div>
  </div>

</section>

CodePudding user response:

It is too simple. Write a function in typescript.

Template (html Component)

<div *ngFor="let cart of cartList">
  <p> price - {{ cart.price }} </p>
</div>
<p> Total Price - {{ totalPrice }} </p>

(TS Component)

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

@Component({
  selector: 'my-app',
  templateUrl: './your.component.html',
  styleUrls: ['./your.component.css'],
})
export class YourComponent implements OnInit {
  cartList = [{ price: 10 }, { price: 20 }, { price: 30 }, { price: 40 }];
  totalPrice = 0;
  ngOnInit(): void {
    this.calculateTotal();
  }
  calculateTotal() {
    this.cartList.map((cart) => {
      this.totalPrice  = cart.price;
    });
  }
}

Evidence

enter image description here

enter image description here

  • Related