How to sum up the values entered in the mat-table column using mat-input in angular2

后端 未结 2 1958
臣服心动
臣服心动 2021-01-18 10:17

I am trying to sum up the values entered in the mat-table column using an input.

I have created a table with 3 columns: Account Id, A

相关标签:
2条回答
  • 2021-01-18 10:33

    Try a reducer:

    <mat-grid-tile> Total: {{dataSource1.data.reduce((summ, v) => summ += v.value, 0)}}</mat-grid-tile>
    
    0 讨论(0)
  • 2021-01-18 10:37

    try this

    In component

     ngOnInit(){
      this.accdetailservice.accountdetails()
      .subscribe(data =>
      this.dataSource1.data= data.map(obj => ({...obj, value: 0}))
      );
     }
    
    
    calculation(){ 
    return dataSource1.data.reduce((summ, v) => summ += parseInt(v.value), 0) 
    }
    

    in Html

    <mat-grid-tile> Total: {{calculation()}}</mat-grid-tile>
    

    also change <input matInput value=0> to <input matInput value="element.value"/>

    Edit:

    as per the chat discussion you need to use value parameter as a dynamic parameter to calculate

    So try this below way

    <ng-container matColumnDef="value">
       <mat-header-cell *matHeaderCellDef> Value </mat-header-cell>
       <mat-cell *matCellDef="let element">
         <ng-container>
           <input  [(ngModel)]="element.value">
         </ng-container>
       </mat-cell>
        </ng-container>
    
    0 讨论(0)
提交回复
热议问题