问题
Explanation: I have a html table with 3 columns namely Price
, Quantity
and Total
. Numers are written below them.
Requirement: I need to multiply price
with Quantity
and bring that value in Total
. I want to do this while leaving the quantity field or on a key press [as i am typing].
Image and code of my form are shared below
Image:
code of invoice.html
<div style="margin-top:15px">
<table>
<tr>
<th></th>
<th>Price</th>
<th>Quantity</th>
<th>Total</th>
<th></th>
</tr>
<tr *ngFor="let items of inVoiceItems2;let i=index;">
<td>{{i+1}}</td>
<td style="width:198px"><input type="text" name="price" [(ngModel)]="inVoiceItems2[i].price" style="width:198px;border:0px"/></td>
<td><input type="text" name="quantity" [(ngModel)]="inVoiceItems2[i].quantity" style="width:198px;border:0px"/></td>
<td><input type="text" name="total" [(ngModel)]="inVoiceItems2[i].total" style="width:198px;border:0px"/></td>
</tr>
</table>
<br>
<input type="button" value="Add New Row" (click)="addRow2()" style="margin-top:5px"/>
<br>
<input type="button" value="Calculate Bill" (click)="calculate_bill()" style="margin-top:5px"/>
</div>
code of invoice.ts
addRow2(){
this.inVoiceItems2.push({'debit':'','credit':''});
}
calculate_bill(){
}
回答1:
To do the calculation when typing in the quantity field, you will need to use the blur
event.
<td><input type="text" name="quantity" [(ngModel)]="inVoiceItems2[i].quantity" style="width:198px;border:0px" (blur)="calculateRowTotal(i)"/></td>
the function would be something like this:
calculateRowTotal(i: number) {
this.inVoiceItems2[i].total = +this.inVoiceItems2[i].price* +this.inVoiceItems2[i].quantity
}
NOTE: this will fail if the value being inserted cannot be converted to a number
回答2:
Here is a basic way, starting from your current setup.
Change the template for the total
input to:
<input type="text" name="total" [ngModel]="getRowSum(inVoiceItems2[i].quantity, inVoiceItems2[i].price)" style="width:198px;border:0px"/>
Create the getRowSum
method in invoice.ts
:
getRowSum(qty, price) {
const sum = qty * price;
return isNaN(sum) ? '' : sum;
}
来源:https://stackoverflow.com/questions/47349108/how-to-calculate-multiplication-of-numbers-in-a-html-table-below-specific-headin