Reputation: 366
I have a angular material table with input fields in it. Need to calculate the total (without button) and display at the bottom. Also when change the input number , should recalculate and display. It calculates and displays sum of what is in the ts file but when changes in the input box, concatenate . HTML code
<ng-container matColumnDef="tuesday">
<th mat-header-cell *matHeaderCellDef> tuesday </th>
<td mat-cell *matCellDef="let transaction">
<mat-form-field>
<input [(ngModel)]="transaction.tuesday" placeholder="Field Name" matInput ="number"/>
</td>
<td mat-footer-cell *matFooterCellDef> {{getTotalCostTuesday() | currency}} </td>
</ng-container>
TS code
transactions: PeriodicElement[] = [
{ project: 'Hydrogen', monday:1, tuesday:2},
{ project: 'Helium', monday:1 ,tuesday: 5 },
{ project: 'Lithium' , monday:1, tuesday: 3},
{ project: 'Beryllium' , monday:1, tuesday: 4 },
];
getTotalCostTuesday() {
return this.transactions.map(t => t.tuesday
).reduce((acc, value) => acc + value, 0);
}
Upvotes: 2
Views: 1101
Reputation: 8316
That concatenation is due to value
(coming from the input field) being a string. Change it to a number before addition.
getTotalCostTuesday() {
return this.transactions.map(t => t.tuesday
).reduce((acc, value) => acc + parseInt(value), 0);
}
Upvotes: 2