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);
   
}

1 Answer 1

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);  
}
Sign up to request clarification or add additional context in comments.

2 Comments

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;
Thanks. I have fixed it with assigning tuesday: any.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.