Lonna
Lonna

Reputation: 355

My total is 0 when I put quantity and price typescript html

In angular 5 I am creating an application where user can select quantity and price of products and once they are done the product price with the quantity would be shown in the total price. This is my code, that display only Total 0

My html code:

<div class="input-field col s12">
      <input formControlName="Quantity" id="Quantity " type="number" class="validate">
    </div>
    <div class="input-field col s12">
      <input formControlName="Unit_price" id="Unit_price" type="number" class="validate">
    </div>
    <div class="input-field col s12">
      <input formControlName="Subtotal" id="Subtotal" type="number" class="validate">
      <label for="Subtotal">Total {{Price}}</label>
    </div>

Ts code:

  Price: number = 0;
  products: Products[];

      countPrice() {
        this.Price = 0;
        for (let p of this.products) {
          this.Price += p.Unit_price * p.Quantity
        }
         }

Can you suggest me, what is the problem, and how to solve this?

Upvotes: 0

Views: 453

Answers (3)

Ankur Rathi
Ankur Rathi

Reputation: 109

You are not calling your function countPrice(). I have updated your code and called the countPrice() in html itself.

<div class="input-field col s12">
  <input formControlName="Quantity" id="Quantity " type="number" class="validate">
</div>
<div class="input-field col s12">
  <input formControlName="Unit_price" id="Unit_price" type="number" class="validate">
</div>
<div class="input-field col s12">
  <input formControlName="Subtotal" id="Subtotal" type="number" class="validate">
  <label for="Subtotal">Total {{countPrice()}}</label>
</div>

Now in your countPrice() function return this.Price Refer the update function for this.

     Price: number = 0;
     products: Products[];

        countPrice() {
            this.Price = 0;
            for (let p of this.products) {
              this.Price += parseInt(p.Unit_price) * parseInt(p.Quantity)
            }
             return this.Price;
             }

Upvotes: 0

Dionisis K
Dionisis K

Reputation: 644

You are not calling countPrice anywhere ( at least with the code you provided) .
So Total * {{Price}} = 0 since Price initial value is 0

Upvotes: 1

ibenjelloun
ibenjelloun

Reputation: 7743

The value you are computing in the countPrice can directly be added to the template like this :

{{ form.values.Quantity * form.values.Unit_price }}

Upvotes: 0

Related Questions