Determine the value added tax in your online shopping basket

Currently, I am in the process of developing a webshop for a pizzeria using Angular, and recently completed work on my cart component. One of the key features I wanted to incorporate was adding a 10% Value-Added Tax (VAT) for each item in the cart and including it in the overall total.

To achieve this functionality, I made modifications to my cart service by defining a new method called 'calcTotal'. This method performs all the necessary calculations to apply the VAT to each item within the cart.

calcTotal() {
    let total: number = 0;
    let vat: number = 0;

    this.cart.forEach((item) => {
      vat = item.price * 0.1;
      total += item.price + vat;
    })
    return total;
  }

In order to make use of these newly added properties, I updated my cart.component.ts file accordingly:

export class CartComponent implements OnInit {
  cart: Imenu[] = [];
  total: number = 0;
  vat: number = 0;


  constructor(private CS: CartService) { }
  ngOnInit(): void {
    this.cart = this.CS.getCart();
    this.total = this.CS.calcTotal();
    this.vat = this.CS.calcTotal();


  }
}

By referencing these properties in my cart.component.html file, I can display the service charge and total value as follows:

 <div class="col-md-5 col-lg-4 order-md-last">
        <p>Service Charge: {{vat}}</p>
        <p>Total Amount: {{total}}</p>
    </div>
</div>

However, currently both the service charge and total amount are displaying identical values. To rectify this discrepancy, I need to outline how the service charge is declared in my cart.service.ts file so that it accurately represents 10% of the total price.

Answer №1

service utilizes the calcTotal method to fetch the total value exclusively.

You could alternatively create a new method for calculating the overall VAT.

calcServiceTotal() {
  let serviceTotal: number = 0;

  this.cart.forEach((val) => {
    serviceTotal += val.price * 0.1;
  });

  return serviceTotal;
}
this.service = this.CS.calcServiceTotal();

Alternatively, modify the calTotal method to provide both the service and total values.

calcTotal() {
  let total: number = 0;
  let serviceTotal: number = 0;

  this.cart.forEach((val) => {
    service = val.price * 0.1;
    serviceTotal += service;
    total += val.price + service;
  });

  return [serviceTotal, total];
}

Utilize destructing assignment to assign values to both service and total.

[this.service, this.total] = this.CS.calcTotal();

The calculated result may appear as: 3.1200000003. Refer to this query for further information: Why does 0.1 + 0.2 return unpredictable float results in JavaScript while 0.2 + 0.3 does not?.

Hence, it is advisable to apply DecimalPipe for displaying decimals accurately.

<p>Service: {{service | number}}</p>
<p>Total: {{total | number}}</p>

Live Demo @ StackBlitz

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The "if(x in obj)" statement in Typescript does not properly narrow down my custom Record

I am struggling with a code snippet where I am trying to check if a string exists in my custom record using the if(x in obj) guard statement, but it seems to not be working as expected. Below is the sample code snippet that is throwing an error: type Ans ...

The Angular component seems to be failing to refresh the user interface despite changes in value

Recently, I created a simple component that utilizes a variable to manage its state. The goal is to have the UI display different content based on changes in this variable. To test this functionality, I implemented the component and used a wait function to ...

Discovering Type Definitions in Nuxt.js Project Without Manual Imports in VSCode: A Step-by-Step Guide

Having issues with VSCode not recognizing type definitions automatically in a Nuxt.js project with TypeScript. I'm looking to avoid manually importing types in every file. Here's my setup and the problem I'm facing: Configuration My tsconfi ...

Unable to activate parameter function until receiving "yes" confirmation from a confirmation service utilizing a Subject observable

Currently, I am working on unit tests for an Angular application using Jasmine and Karma. One of the unit tests involves opening a modal and removing an item from a tree node. Everything goes smoothly until the removeItem() function is called. This functi ...

Angular - Utilizing nested arrays for efficient file uploading

I am currently working on building a file uploader using Angular. My goal is to be able to upload different types of files, with each button capable of uploading multiple files at once. However, I am running into an issue where the uploaded files are not b ...

Arranging a list of objects with a designated starting value to remain at the forefront

Consider the array and variable shown below: array = ['complete','in_progress','planned']; value = 'planned'; The goal is to always sort the array starting with the 'value' variable, resulting in: array ...

Limit the covariance of properties in generic arguments

When I define a generic argument of object type with specific mandatory properties (for example, in this function it requires the object to have timestamp: string), TypeScript allows for using a more specialized attribute type as a generic argument - as sh ...

Guide on converting a JSON object into a TypeScript Object

I'm currently having issues converting my JSON Object into a TypeScript class with matching attributes. Can someone help me identify what I'm doing wrong? Employee Class export class Employee{ firstname: string; lastname: string; bi ...

Challenges encountered when using Tailwindcss and Nextjs with class and variables

Hey there, I'm currently facing a major issue with tailwindcss + nextjs... The problem lies in setting classes using a variable. Although the class is defined in the css, tailwind fails to convert it into a style. This is how I need it to be: https ...

Angular - Customizing button bindings for various functions

As a newcomer to Angular and TypeScript, I am faced with the task of creating a customizable button that can display text, an icon, or both. For example: button-icon-text-component.html <button> TEST BUTTON </button> app.component.html & ...

Creating formGroups dynamically for each object in an array and then updating the values with the object data

What I am aiming to accomplish: My goal is to dynamically generate a new formGroup for each recipe received from the backend (stored in this.selectedRecipe.ingredients) and then update the value of each formControl within the newly created formGroup with t ...

Using a pipe filter to implement a search feature in an Ionic search bar

Hey everyone, I'm facing a little issue here. I created a pipe filter to sort through some data, but now I need to include two more filters and I'm not sure how to go about it within this pipe. Below is an example of the pipe I have created: ...

What are the steps to incorporating a personalized component into an extension?

I am working on a TypeScript file that includes a class inheriting cc.Component. My goal is to package this file as an extension and make it easily accessible within the editor, allowing users to add it to a node with ease. What steps should I take to ac ...

Tips for preloading icon font in Angular server-side rendering (SSR)

Is it possible to preload icons and fonts before the HTML content is rendered? I have been using a preload strategy to try and achieve this. index.html <!doctype html> <html lang="en"> <head> <meta charset="utf-8&quo ...

Angular input field with the ability to add and remove multiple options

Users can enter multiple emails to be added to a list, and they have the option to remove emails from the list. https://i.sstatic.net/vnHpJ.png ...

Creating a dynamic CSS height for a div in Angular CLI V12 with variables

Exploring Angular development is a new venture for me, and I could use some guidance on how to achieve a variable CSS height in Angular CLI V12. Let me simplify my query by presenting it as follows: I have three boxes displayed below. Visual representatio ...

Leverage the capabilities of one service within another service

I have been working on enhancing the functionality of Http so that when a user encounters a 403 error, their user information is removed and they are redirected to the login page. I have shared an example of AuthHttp below for reference. @Injectable() ...

Moment.js is stating that there is no property called 'toISOString' on the type '{}'

I'm facing an issue with my code - the `value.toISOString()` function was working fine until now, but suddenly it's throwing a compiler error. I recently upgraded from Angular 7 to 8, which also bumped up the Typescript version to 3.4.5. Any sugg ...

Convert the generic primitive type to a string

Hello, I am trying to create a function that can determine the primitive type of an array. However, I am facing an issue and haven't been able to find a solution that fits my problem. Below is the function I have written: export function isGenericType ...

Dynamic Angular form with nested elements

Need help creating a nested form following the example from angular.io documentation: https://stackblitz.com/angular/pbdkbbnmrdg The objective is to include two DropdownQuestion elements from question.service.ts within a child formgroup called "details", ...