2

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);
   
}
Sz2013
  • 288
  • 1
  • 5
  • 18

1 Answers1

2

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);  
}
Lakshya Thakur
  • 8,030
  • 1
  • 12
  • 39
  • I did and it give this error "(parameter) value: number Argument of type 'number' is not assignable to parameter of type 'string'.ts(2345)" . I already have it declared tuesday: number; – Sz2013 Feb 26 '21 at 11:31
  • Thanks. I have fixed it with assigning tuesday: any. – Sz2013 Feb 26 '21 at 11:36